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

yipeiwu_com6年前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'

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

相关文章

python实现获取Ip归属地等信息

如果你有一批IP地址想要获得这些IP具体的信息,比如归属国家,城市等,最好的办法当时是调用现有的api接口来获取,我在之前就写过一篇文章,是关于我的博客被莫名攻击的时,就有获取过一批IP...

python使用7z解压软件备份文件脚本分享

要求安装: 1.Python2.7z解压软件 backup_2.py 复制代码 代码如下:# Filename: backup_2.py '''Backup files. &n...

Python 实现数组相减示例

问题描述: 有2个数组如下 a = [3,3,3,4,4,4,5,6,7] b = [3,3,4,4] 第1题:从数组a中删除所有在数组b中出现过的元素。对于上例来说,a删除结束...

spark: RDD与DataFrame之间的相互转换方法

spark: RDD与DataFrame之间的相互转换方法

DataFrame是一个组织成命名列的数据集。它在概念上等同于关系数据库中的表或R/Python中的数据框架,但其经过了优化。DataFrames可以从各种各样的源构建,例如:结构化数据...

python搜索指定目录的方法

本文实例讲述了python搜索指定目录的方法。分享给大家供大家参考。具体分析如下: #------------------------------------- # Nam...