#输出结果到屏幕上,并不返回执行状态
os.system('dir')
#保存命令的执行结果输出
ret = os.popen('dir').read()python
问题:上面2条是把命令结果保存下来了,可是返回状态没了,也就没办法判断该命令是否执行成功。例如:shell
解决方式: 既想要执行结果邮箱要执行状态请使用subprocess模块。windows
注意:
在python2.7里有个commands模块,能够经过commands.getstatusoutput("dir")查看系统命令的执行状态,可是在3.5里就已经弃用了。
在3.5里新出了一个subprocess模块来替换os.system、os.spawn*、 commands等模块的功能。python2.7
做用:函数
1 #python解析shell命令: 2 subprocess.run(["df","-h"]) 3 4 #不用python解析shell命令:(shell=True) 5 subprocess.run("df -h |grep sda1",shell=True)
1、执行命令,返回状态值,不返回结果:(call)spa
1 一、列表形式(shell = False) 2 ret = subprocess.call(["ls","-l"],shell=False) 3 print(ret) 4 5 二、字符串形式(shell=True) 6 ret = subprocess.call("ls -l",shell=True) 7 print(ret)
2、执行命令,若是状态码是0,则返回0,不然报异常,不反悔结果:(check_call)code
1 一、列表形式(shell = False) 2 ret = subprocess.check_call(["ls","-l"],shell=False) 3 print(ret) 4 5 二、字符串形式(shell=True) 6 ret = subprocess.check_call("ls -l",shell=True) 7 print(ret)
3、执行命令,若是状态码是 0 ,则返回执行结果,不然抛异常:(check_output)对象
1 一、列表形式(shell = False) 2 ret = subprocess.check_output(["echo","hello world"],shell=False) 3 print(ret) 4 5 二、字符串形式(shell=True) 6 ret = subprocess.check_output("exit 1",shell=True) 7 print(ret)
4、本地建立目录:blog
使用subprocess.Popen(...) 用于执行复杂的系统命令(上面的方法在后台实际就是调用的Popen)继承
(二)、输入便可获得输出,如:ifconfig
1 import subprocess 2 ret1 = subprocess.Popen(["mkdir","t1"]) 3 ret2 = subprocess.Popen("mkdir t2", shell=True)
5、跳转到指定目录而后在建立目录:
输入进行某环境,依赖再输入,如:python
1 obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
6、经过管道进入交互方式:
1 import subprocess 2 3 #下面的stdin,stdout,stderr至关于三个管道,之后要想写内容的时候经过管道就能够写。 4 obj = subprocess.Popen(["python"], #写了一个python,就会进入python解释器,obj就至关于定义一个对象。 5 stdin=subprocess.PIPE, #专门写的管道1 6 stdout=subprocess.PIPE, #那正常结果的管道2 7 stderr=subprocess.PIPE, #用来拿错误的管道3 8 universal_newlines=True) 9 10 #向管道里面写数据,下面2个print就至关于写了2行数据。(至关于在终端把命令输入进去了,剩下的就是拿结果) 11 obj.stdin.write("print(1)\n") 12 obj.stdin.write("print(2)") 13 obj.stdin.close() #表示中止写入 14 15 #能够到stdout的管道中取结果,读到正常输出的结果值 16 cmd_out = obj.stdout.read() 17 obj.stdout.close() 18 19 #若是出现错误,能够到stderr中提取报错结果 20 cmd_error = obj.stderr.read() 21 obj.stderr.close() 22 23 24 #最后输出执行命令结果 25 print(cmd_out) 26 print(cmd_error)
7、合并stdout和stderr的输入结果值:(communicate):
1 import subprocess 2 3 obj = subprocess.Popen(["python"], 4 stdin=subprocess.PIPE, 5 stdout=subprocess.PIPE, 6 stderr=subprocess.PIPE, 7 universal_newlines=True) 8 obj.stdin.write("print(1)\n") 9 obj.stdin.write("print(2)") 10 11 out_error_list = obj.communicate() #其实这个命令就是去stdout和stderr两个管道里去拿返回out和error值,不用再次编辑。 12 print(out_error_list)
8、执行简单的命令:
1 import subprocess 2 obj = subprocess.Popen(["python"], 3 stdin=subprocess.PIPE, 4 stdout=subprocess.PIPE, 5 stderr=subprocess.PIPE, 6 universal_newlines=True) 7 out_error_list = obj.communicate('print("hello")') 8 print(out_error_list)