commands模块

来源:互联网 发布:铸造模拟分析软件 编辑:程序博客网 时间:2024/05/29 13:20

commands模块只使用与linux的shell模式下

[root@geenk03 opt]# cat test.py#!/usr/bin/env pythonimport commandscmd = 'ls /home/'a = commands.getoutput(cmd)print (type(a))print (a)

在上面我们在执行shell命令的时候,我们的shell命令可能执行报错,或者异常退出,我们就要有一个条件来判断shell最终执行的结果是什么,commands.getstatusoutput(cmd)的返回结果有两个值

[root@geenk03 opt]# python test.py<type 'str'>aa.txtadminapache-maven-3.3.9-bin.tar.gzDATAeasyexpress_controller.logeasypush_error.logelk
[root@geenk03 opt]# cat test1.py#!/usr/bin/env python#coding:utf-8import commandscmd = 'ps -aux |grep nginx'# commands.getstatusoutput(cmd) 返回的是一个tuplet = commands.getstatusoutput(cmd)#result返回的是str,status 返回的是int#result就是命令的结果#如果键入的命令正确,则status为0,否则不为0status,result = commands.getstatusoutput(cmd)print (type(t))print (type(result))print(result)print(type(status))print (status)
[root@geenk03 opt]# python test1.py<type 'tuple'><type 'str'>Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.8/FAQroot     24724  0.0  0.0 106108  1136 pts/0    S+   15:20   0:00 sh -c { ps -aux |grep nginx; } 2>&1root     24726  0.0  0.0 103336   848 pts/0    S+   15:20   0:00 grep nginx<type 'int'>0
原创粉丝点击