• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C++/Php/Python 语言执行shell命令 - 旭东的博客

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

C++/Php/Python 语言执行shell命令

编程中经常需要在程序中使用shell命令来简化程序,这里记录一下。

1. C++ 执行shell命令

 1 #include <iostream>
 2 #include <string>
 3 #include <stdio.h>
 4 
 5 int exec_cmd(std::string cmd, std::string &res){
 6     if (cmd.size() == 0){   //cmd is empty 
 7         return -1;
 8     }
 9 
10     char buffer[1024] = {0};
11     std::string result = "";
12     FILE *pin = popen(cmd.c_str(), "r");
13     if (!pin) { //popen failed 
14         return -1;
15     }
16 
17     res.clear();
18     while(!feof(pin)){
19         if(fgets(buffer, sizeof(buffer), pin) != NULL){
20             result += buffer;
21         }
22     }
23 
24     res = result;
25     return pclose(pin); //-1:pclose failed; else shell ret
26 }
27 
28 int main(){
29     std::string cmd = "ls -ial";
30     std::string res;
31 
32     std::cout << "ret = " << exec_cmd(cmd, res) << std::endl;
33     std::cout << res << std::endl;
34 
35     return 0;
36 }

2. Php执行shell命令

1 <?php
2     $cmd = "wc -l ./test.php";
3     exec($cmd, $output, $code);
4 
5     echo $code."\n";
6     print_r($output);
7 ?>

3. Python执行shell命令

1 import commands
2 
3 status, output = commands.getstatusoutput(\'ls -lt\')
4 
5 print status
6 print output

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Log4php 使用心得发布时间:2022-07-10
下一篇:
php多进程pcntl学习-僵尸进程php多进程pcntl学习(一)发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap