Python subprocess方法

 1 import subprocess
 2 #subprocess.call("df -h",shell=True,stdout=subprocess.PIPE)#打印到视图,但是不能保存,也不能保存变量
 3 
 4 #a = subprocess.Popen("df -h",shell=True,stdout=subprocess.PIPE)
 5 #使用原生的shell
 6 #此方法的意思是开一个新的shell子进程执行"df -h"这个命令,如果不加stdout=subprocess.PIPE那么就获取不到返回值,加上的意思是将执行结果返回给给stdout管道输出出来。
 7 #print(a.stdout.read())
 8 #-------------------------------------------
 9 #需要交互的命令示例
10 import subprocess
11 obj = subprocess.Popen(["python"],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)#相当于新开一个shell进入python交互式命令行,然后标准输入输出全都通过管道输出出来
12 obj.stdin.write('print (1) 
')
13 obj.stdin.write('print (2) 
')
14 obj.stdin.write('print (3) 
')
15 obj.stdin.write('print (4) 
')
16 
17 out_error_list = obj.communicate(timeout=10)
18 print(out_error_list)
19 
20 #常用使用subprocess方法
21 def runCmd(cmd):
22     res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
23     sout,serr = res.communicate()
24     #print (sout,serr)
25     #return res.returncode, sout, serr, res.pid
26     return sout, serr
原文地址:https://www.cnblogs.com/Presley-lpc/p/9630007.html