博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++/Php/Python 语言执行shell命令
阅读量:6983 次
发布时间:2019-06-27

本文共 1039 字,大约阅读时间需要 3 分钟。

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

1. C++ 执行shell命令

1 #include 
2 #include
3 #include
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 ret26 }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 

3. Python执行shell命令

1 import commands2 3 status, output = commands.getstatusoutput('ls -lt')4 5 print status6 print output

 

转载地址:http://ejxpl.baihongyu.com/

你可能感兴趣的文章
Windows Phone笔记索引(总)
查看>>
1分钟破解3dState '学习版'得一些版权信息。
查看>>
我和linux
查看>>
动态调用webservice
查看>>
Java刷题知识点之方法覆盖(方法重写)和方法重载的区别
查看>>
爆牙齿的世界杯日记(小组首轮)
查看>>
ITTC数据挖掘平台介绍(四) 框架改进和新功能
查看>>
JDK5.0新特性系列---11.4线程 Condition
查看>>
Software development --daily scrum team
查看>>
【原】macbook不睡眠的排查与解决
查看>>
用HttpListener做web服务器,简单解析post方式过来的参数、上传的文件
查看>>
ubuntu 12.04解决Broadcom STA无线网卡驱动安装失败解决
查看>>
【CSWS2014 Summer School】互联网广告中的匹配和排序算法-蒋龙(上)
查看>>
连续启动 crash 自修复技术实现与原理解析
查看>>
C#基础回顾:GridView全选演示
查看>>
Wintel物联网平台-Windows IoT新手入门指南
查看>>
解决linux下无线网卡被物理禁用问题
查看>>
批处理脚本, 读取文件并字符串替换
查看>>
SQL Server误区30日谈-Day27-使用BACKUP ... WITH CHECKSUM可以替代DBCC CheckDB
查看>>
Message,MessageQueue,Looper,Handler详解+实例
查看>>