python中command执行shell命令脚本方法

在Python中有一个模块commands也很容易做到以上的效果.
看一下三个函数:
1). commands.getstatusoutput(cmd)
用os.popen()执行命令cmd, 然后返回两个元素的元组(status, result),其中 status为int类型,result为string类型。cmd执行的方式是{ cmd ; } 2>&1, 这样返回结果里面就会包含标准输出和标准错误.


2). commands.getoutput(cmd)
只返回执行的结果, 忽略返回值.


3). commands.getstatus(file) #现已被弃用
返回ls -ld file执行的结果.


看一下这些函数使用的例子:

>>> 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'

猜你喜欢

转载自www.cnblogs.com/lhlblog/p/10359260.html
今日推荐