在C/python中执行linux命令并得到返回值以及输出
2012-11-21 09:52
591 查看
一般来说,用shell的方便之处在于,能够直接调用linux系统命令,方便的得到结果。
但是shell scprit的约束重重(这里不再讲了)。下面说一下在C和python中如何调用linux命令、得到返回值并得到输出
1. python,使用os库/commands库
方法1)使用commands.getstatusoutput方法,这是一个神奇的方法,能够直接得到返回值以及命令输出。官网说明:http://docs.python.org/library/commands.html
status是返回值,ouput是输出
但是这种方法存在一个问题,就是如果命令中(cmdstr)含有&符号,这个命令会出错,此时,需要使用os.system方法
方法2)使用os.system
status = os.system(cmdstr)
status是返回值,得不到输出,检查的方法如上
方法3)使用os.popen,这是一个和C相似的方法,既能得到返回值,也能得到输出,缺点是用起来稍微麻烦一些
p相当于打开的一个文件
2. C中使用#include <stdio.h> 库,下面是我写的一个调用系统命令的函数。
使用popen,这个好处就是既能得到返回值也能得到输出,我将调用以及返回值判断封装了一下,便于平时使用
但是shell scprit的约束重重(这里不再讲了)。下面说一下在C和python中如何调用linux命令、得到返回值并得到输出
1. python,使用os库/commands库
import os import commands
方法1)使用commands.getstatusoutput方法,这是一个神奇的方法,能够直接得到返回值以及命令输出。官网说明:http://docs.python.org/library/commands.html
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 x p.close()
p相当于打开的一个文件
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命令并得到返回值以及输出
- python 带参数执行命令并得到输出结果
- 记录linux设置定时执行python脚本以及输出到指定文件
- Python远程执行Linux命令
- IPython下执行shell命令-魔力函数(alias store rehash)- 千月的python linux 系统管理指南学习笔记(6)
- Python 执行linux 命令
- 使用cocos studio打包apk报错或者用python打包出错,执行命令出错,返回值:
- Android点滴(1) -- 执行Linux命令并且获得输出的结果
- linux下执行命令输出乱码解决方案
- python中执行linux命令(调用linux命令)
- python 执行linux系统命令
- linux命令执行返回值
- 由linux命令行下的两条命令来阐释输出结果和返回值的区别
- python执行系统命令后获取返回值的几种方式
- linux下通过java执行sh脚本,得到返回值
- python 执行命令 获取返回值 和 print内容 用module commands
- 使用cocos studio打包apk报错或者用python打包出错,执行命令出错,返回值:
- 分析RunTime执行命令以及得到返回值
- 在android中如何编译连接 .c 的可执行文件 Android点滴(1) -- 执行Linux命令并且获得输出的结果
- python paramiko 向linux执行命令和发送接收文件