Python中subprocess模块的使用

来源:互联网 发布:在淘宝搜血滴子 编辑:程序博客网 时间:2024/05/21 06:25

执行命令:

[python] view plaincopy
  1. >>> subprocess.call(["ls""-l"])  
  2. 0  
  3. >>> subprocess.call("exit 1", shell=True)  
  4. 1  

测试调用系统中cmd命令,显示命令执行的结果:

[python] view plaincopy
  1. x=subprocess.check_output(["echo""Hello World!"],shell=True)  
  2.   
  3. print(x)  
  4. "Hello World!"  

测试在python中显示文件内容:

[python] view plaincopy
  1. y=subprocess.check_output(["type""app2.cpp"],shell=True)  
  2.   
  3. print(y)  
  4. #include <iostream>     
  5. using namespace std;    
  6. ......  
查看ipconfig -all命令的输出,并将将输出保存到文件tmp.log中:

[python] view plaincopy
  1. handle = open(r'd:\tmp.log','wt')  
  2. subprocess.Popen(['ipconfig','-all'], stdout=handle)  

查看网络设置ipconfig -all,保存到变量中:

[python] view plaincopy
  1. output = subprocess.Popen(['ipconfig','-all'], stdout=subprocess.PIPE,shell=True)  
  2. oc=output.communicate()#取出output中的字符串  
  3. #communicate() returns a tuple (stdoutdata, stderrdata).  
  4. print(oc[0]) #打印网络信息  
  5.   
  6. Windows IP Configuration  
  7.   
  8.         Host Name . . . . .  
我们可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe):

[python] view plaincopy
  1. child1 = subprocess.Popen(["dir","/w"], stdout=subprocess.PIPE,shell=True)  
  2. child2 = subprocess.Popen(["wc"], stdin=child1.stdout,stdout=subprocess.PIPE,shell=True)  
  3. out = child2.communicate()  
  4. print(out)  
  5.  ('      9      24     298\n'None)  

如果想频繁地和子线程通信,那么不能使用communicate();因为communicate通信一次之后即关闭了管道.这时可以试试下面的方法:

[plain] view plaincopy
  1. p= subprocess.Popen(["wc"], stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)  
  2. p.stdin.write('your command')  
  3. p.stdin.flush()  
  4. #......do something   
  5. try:  
  6.     #......do something  
  7.     p.stdout.readline()  
  8.     #......do something  
  9. except:  
  10.     print('IOError')  
  11. #......do something more  
  12. p.stdin.write('your other command')  
  13. p.stdin.flush()  
  14. #......do something more  

0 0
原创粉丝点击