pythonshell怎么运⾏多⾏代码_python中执⾏shell命令的⼏个
⽅法⼩结(转载)
python怎么读的
python中执⾏shell命令的⼏个⽅法⼩结
投稿:junjie 字体:[增加 减⼩] 类型:转载 时间:2014-09-18 我要评论
这篇⽂章主要介绍了python中执⾏shell命令的⼏个⽅法,本⽂⼀共给出3种⽅法实现执⾏shell命令,需要的朋友可以参考下
最近有个需求就是页⾯上执⾏shell命令,第⼀想到的就是os.system,
复制代码 代码如下:
os.system('cat /proc/cpuinfo')
但是发现页⾯上打印的命令执⾏结果 0或者1,当然不满⾜需求了。
尝试第⼆种⽅案 os.popen()
复制代码 代码如下:
output = os.popen('cat /proc/cpuinfo')
ad()
通过 os.popen() 返回的是 file read 的对象,对其进⾏读取 read() 的操作可以看到执⾏的输出。但是⽆法读取程序执⾏的返回值)
尝试第三种⽅案 statusoutput() ⼀个⽅法就可以获得到返回值和输出,⾮常好⽤。
复制代码 代码如下:
(status, output) = statusoutput('cat /proc/cpuinfo')
print status, output
Python Document 中给的⼀个例⼦,
复制代码 代码如下:
>>> import commands
>>> statusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> statusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> statusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> utput('ls /bin/ls')
'/bin/ls'
>>> status('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。