C++/Php/Python 語言執(zhí)行shell命令的方法(推薦)
更新時間:2017年03月31日 14:09:05 投稿:jingxian
下面小編就為大家?guī)硪黄狢++/Php/Python 語言執(zhí)行shell命令的方法(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
編程中經(jīng)常需要在程序中使用shell命令來簡化程序,這里記錄一下。
1. C++ 執(zhí)行shell命令
#include <iostream>
#include <string>
#include <stdio.h>
int exec_cmd(std::string cmd, std::string &res){
if (cmd.size() == 0){ //cmd is empty
return -1;
}
char buffer[1024] = {0};
std::string result = "";
FILE *pin = popen(cmd.c_str(), "r");
if (!pin) { //popen failed
return -1;
}
res.clear();
while(!feof(pin)){
if(fgets(buffer, sizeof(buffer), pin) != NULL){
result += buffer;
}
}
res = result;
return pclose(pin); //-1:pclose failed; else shell ret
}
int main(){
std::string cmd = "ls -ial";
std::string res;
std::cout << "ret = " << exec_cmd(cmd, res) << std::endl;
std::cout << res << std::endl;
return 0;
}
2. Php執(zhí)行shell命令
<?php $cmd = "wc -l ./test.php"; exec($cmd, $output, $code); echo $code."\n"; print_r($output); ?>
3. Python執(zhí)行shell命令
import commands
status, output = commands.getstatusoutput('ls -lt')
print status
print output
以上這篇C++/Php/Python 語言執(zhí)行shell命令的方法(推薦)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:
相關(guān)文章
最新C/C++中的new和delete的實現(xiàn)過程小結(jié)
這篇文章主要介紹了C/C++中的new和delete的實現(xiàn)過程,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06
C++11關(guān)于auto關(guān)鍵字的使用示例
今天小編就為大家分享一篇關(guān)于C++11關(guān)于auto關(guān)鍵字的使用示例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2018-12-12

