Python的subprocess子进程和管道进行交互

本文转载,原文地址:http://blog.csdn.net/marising/article/details/6551692

在很久以前,我写了一个系列,Python和C和C++的交互,如下

http://blog.csdn.net/marising/archive/2008/08/28/2845339.aspx

目的是解决Python和C/C++的互操作性的问题,假如性能瓶颈的地方用C来写,而一些外围工作用Python来完成,岂不是完美的结合。

今天发现了更方便的方式,就是用subprocess模块,创建子进程,然后用管道来进行交互,而这种方式在shell中非常普遍,比如:cat xxx.file | test.py 就是用的管道,另外,在hadoop中stream模式就是用的管道。

其实在python中,和shell脚本,其他程序交互的方式有很多,比如:

os.system(cmd),os.system只是执行一个shell命令,不能输入、且无返回

os.open(cmd),可以交互,但是是一次性的,调用都少次都会创建和销毁多少次进程,性能太差

 

所以,建议用subprocess,但是subprocess复杂一些,可以参考python docs:

http://docs.python.org/library/subprocess.html

 

先看一个简单的例子,调用ls命令,两者之间是没有交互的:

 
  1. import subprocess  
  2. p = subprocess.Popen('ls')  

 

再看在程序中获取输出的例子:

 
  1. import subprocess  
  2. p = subprocess.Popen('ls',stdout=subprocess.PIPE)  
  3. print p.stdout.readlines()  

 

再看看有输入,有输出的例子,父进程发送'say hi',子进程输出 test say hi,父进程获取输出并打印

  1. #test1.py  
  2. import sys  
  3. line = sys.stdin.readline()  
  4. print 'test',line  
  5. #run.py  
  6. from subprocess import *  
  7. p =Popen('./test1.py',stdin=PIPE,stdout=PIPE)  
  8. p.stdin.write('say hi/n')  
  9. print p.stdout.readline()  
  10. #result  
  11. test say hi  

 

看看连续输入和输出的例子

test.py

  1. import sys  
  2. while True:  
  3.         line = sys.stdin.readline()  
  4.         if not line:break  
  5.         sys.stdout.write(line)  
  6.         sys.stdout.flush()  

 

run.py

  1. import sys  
  2. from subprocess import *  
  3. proc = Popen('./test.py',stdin=PIPE,stdout=PIPE,shell=True)  
  4. for line in sys.stdin:  
  5.         proc.stdin.write(line)  
  6.         proc.stdin.flush()  
  7.         output = proc.stdout.readline()  
  8.         sys.stdout.write(output)  

 

注意,run.py的flush和test.py中的flush,要记得清空缓冲区,否则程序得不到正确的输入和输出

 

C/C++的类似,伪代码如下

  1. char* line = new char[2048];  
  2. while (fgets(line, 2028, stdin)) {  
  3.     printf(line);  
  4.     fflush(stdout);//必须清空缓冲区  

Popen其他参数的设置,请参考python docs。

原文链接: https://www.cnblogs.com/catmelo/archive/2013/03/03/2941711.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    Python的subprocess子进程和管道进行交互

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/79476

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午7:03
下一篇 2023年2月9日 下午7:03

相关推荐