在C/python中执行linux命令并得到返回值以及输出
来源:互联网 发布:数据分析经理 编辑:程序博客网 时间:2024/05/18 12:04
一般来说,用shell的方便之处在于,能够直接调用linux系统命令,方便的得到结果。
但是shell scprit的约束重重(这里不再讲了)。下面说一下在C和python中如何调用linux命令、得到返回值并得到输出
1. python,使用os库/commands库
方法1)使用commands.getstatusoutput方法,这是一个神奇的方法,能够直接得到返回值以及命令输出。官网说明:http://docs.python.org/library/commands.html
import osimport commands status,output=commands.getstatusoutput(cmdstr)#***********************下面代码是判断返回值********************************************************** if False==os.WIFEXITED(status) or 0!=os.WEXITSTATUS(status): self.logging.info("check port false. port [%s] has not been listened. cmdstr: [%s]", port, cmdstr) return False self.logging.info("check port true. port [%s] has been listened. cmdstr: [%s]", cmdstr) return True status是返回值,ouput是输出#但是这种方法存在一个问题,就是如果命令中(cmdstr)含有&符号,这个命令会出错,此时,需要使用os.system方法
方法2)使用os.system
status = os.system(cmdstr)
status是返回值,得不到输出,检查的方法如上
方法3)使用os.popen,这是一个和C相似的方法,既能得到返回值,也能得到输出,缺点是用起来稍微麻烦一些
p=os.popen('ssh 10.3.16.121 ps aux | grep mysql')x=p.read()print xp.close()
p相当于打开的一个文件
方法4) 使用 subprocess模块,这个是比较新的模块,要替代
os.systemos.spawn*os.popen*popen2.*commands.*这些模块。 subprocess应用实例:
subprocess.call(args,*, stdin=None, stdout=None, stderr=None, shell=False)
import subprocesscmd=['ls','-l']subprocess.call(cmd)subprocess.call('cat /etc/passwd',shell=True)
2. C中使用#include <stdio.h> 库,下面是我写的一个调用系统命令的函数。
使用popen,这个好处就是既能得到返回值也能得到输出,我将调用以及返回值判断封装了一下,便于平时使用
#include <stdio.h> int execute_cmd(const char *cmdstr, char * retstr, int len) { FILE *fpin=NULL; if(NULL==(fpin=popen(cmdstr,"r"))) { WRITE_LOG_EX(UL_LOG_FATAL,"execute command '%s' failed: %s",cmdstr,strerror(errno)); return 1; } if(NULL == fgets(retstr, len, fpin)) { retstr = NULL; } return 0; }
- 在C/python中执行linux命令并得到返回值以及输出
- 在C/python中执行linux命令并得到返回值以及输出
- 在VC下执行DOS命令并得到返回结果
- 在VC下执行DOS命令并得到输出
- 在python中执行shell命令,并以字符串形式返回命令执行结果
- 分析RunTime执行命令以及得到返回值
- Linux C 执行shell命令并获取返回结果
- python学习系列(九) --- 带参数执行命令并得到输出结果
- Python中执行外部命令并捕获双向输出
- 在C#中执行dos命令并返回结果字符串
- 在VC下执行DOS命令并得到输出(转)
- 在VC下执行DOS命令并得到输出(转)
- 在VC下执行DOS命令并得到输出(转)
- python中subprocess.Popen执行命令并持续获取返回值
- C语言执行Linux的shell命令并获得返回值
- C语言执行Linux的shell命令并获得返回值
- C语言执行Linux的shell命令并获得返回值
- C语言执行Linux的shell命令并获得返回值
- 《HTML5与CSS3权威指南》学习笔记1
- Gallery相片滑动实例
- 浅谈游戏辅助开发
- linux下查看进程内存使用情况
- 嵌入式系统设备驱动接口的C#编程
- 在C/python中执行linux命令并得到返回值以及输出
- 由个人经验分析百度零收录的原因
- VC/MFC子窗体向父窗体传递参数的几种方法
- java 线程池
- 从程序员到项目经理
- 从程序员到项目经理(二)
- android 权限大全
- 网络拓扑介绍
- const int *p与int *const p的区别