C++/Php/Python 語(yǔ)言執(zhí)行shell命令的方法(推薦)
編程中經(jīng)常需要在程序中使用shell命令來(lái)簡(jiǎn)化程序,這里記錄一下。
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 語(yǔ)言執(zhí)行shell命令的方法(推薦)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Qt利用tablewidget模擬手指實(shí)現(xiàn)滑動(dòng)
這篇文章主要為大家詳細(xì)介紹了Qt如何利用tablewidget模擬手指實(shí)現(xiàn)滑動(dòng)效果,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Qt有一定的幫助,需要的可以參考一下2023-01-01Qt中簡(jiǎn)單的按鈕槽函數(shù)傳遞參數(shù)方法
這篇文章主要介紹了Qt中簡(jiǎn)單的按鈕槽函數(shù)傳遞參數(shù)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11C++ 多態(tài)性虛函數(shù)和動(dòng)態(tài)綁定學(xué)習(xí)筆記
這篇文章主要為大家介紹了C++ 多態(tài)性虛函數(shù)和動(dòng)態(tài)綁定學(xué)習(xí)筆記,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10基于OpenCv的運(yùn)動(dòng)物體檢測(cè)算法
這篇文章主要為大家詳細(xì)介紹了基于OpenCv的運(yùn)動(dòng)物體檢測(cè)算法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01從匯編看c++中函數(shù)里面的static關(guān)鍵字的使用說(shuō)明
c++中的static關(guān)鍵字使得函數(shù)里面的局部變量的存活期不在局限于函數(shù)里面,而是變?yōu)樵谡麄€(gè)程序生命期里面都有效2013-05-05C語(yǔ)言實(shí)現(xiàn)打印數(shù)組以及打印注意事項(xiàng)說(shuō)明
這篇文章主要介紹了C語(yǔ)言實(shí)現(xiàn)打印數(shù)組以及打印注意事項(xiàng)說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01