码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-03-25 14:07:04      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:test   执行   c++   shell命令   import   failed   com   code   port   

编程中经常需要在程序中使用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
技术分享

 

from:http://www.cnblogs.com/xudong-bupt/p/6218140.html

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

标签:test   执行   c++   shell命令   import   failed   com   code   port   

原文地址:http://www.cnblogs.com/jiu0821/p/6616633.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!