python获取shell返回值

来源:互联网 发布:苹果隐藏图标软件 编辑:程序博客网 时间:2024/05/20 05:09


在python中调用shell,为了实现流程控制,需要捕获shell的返回值


as咱们都知道,shell正常执行的返回为0,失败或异常为非0,


在python中可以通过,如下方式获取到执行的返回状态码


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



0 0