python中执行shell命令的几个方法小结

yipeiwu_com5年前Python基础

最近有个需求就是页面上执行shell命令,第一想到的就是os.system,

复制代码 代码如下:

os.system('cat /proc/cpuinfo')

但是发现页面上打印的命令执行结果 0或者1,当然不满足需求了。

尝试第二种方案 os.popen()

复制代码 代码如下:

output = os.popen('cat /proc/cpuinfo')
print output.read()

通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。但是无法读取程序执行的返回值)

尝试第三种方案 commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。

复制代码 代码如下:

(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output

Python Document 中给的一个例子,
复制代码 代码如下:

>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

最后页面上还可以根据返回值来显示命令执行结果。

相关文章

微信公众号token验证失败解决方案

我用的是python3+,而官网给的例子是python2的写法。问题就在python版本不同。 下面是截取官方的实例代码的一部分 list = [token, timestamp,...

python发送多人邮件没有展示收件人问题的解决方法

背景: 工作过程中需要对现有的机器、服务做监控,当服务出现问题后,邮件通知对应的人 问题: 使用python 2.7自带的email库来进行邮件的发送,但是发送后没有展示收件人列表内容...

Python 生成一个从0到n个数字的列表4种方法小结

我就废话不多说了,直接上代码吧! 第一种 def test1(): l = [] for i in range(1000): l = l + [i] 第二种(app...

在Python中使用base64模块处理字符编码的教程

在Python中使用base64模块处理字符编码的教程

Base64是一种用64个字符来表示任意二进制数据的方法。 用记事本打开exe、jpg、pdf这些文件时,我们都会看到一大堆乱码,因为二进制文件包含很多无法显示和打印的字符,所以,如果要...

python中的字典操作及字典函数

字典 dict_fruit = {'apple':'苹果','banana':'香蕉','cherry':'樱桃','avocado':'牛油果','watermelon':'西瓜'...