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

来源:互联网 发布:华为网络配置实例 编辑:程序博客网 时间:2024/04/28 01:13

在很久以前,我写了一个系列,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命令,两者之间是没有交互的:

[python] view plaincopy
  1. import subprocess  
  2. p = subprocess.Popen('ls')  
 

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

[c-sharp] view plaincopy
  1. import subprocess  
  2. p = subprocess.Popen('ls',stdout=subprocess.PIPE)  
  3. print p.stdout.readlines()  
 

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

 

[python] view plaincopy
  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

[python] view plaincopy
  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

[python] view plaincopy
  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++的类似,伪代码如下

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

Popen对象

该对象提供有不少方法函数可用。而且前面已经用到了wait()/poll()/communicate()

poll()

检查是否结束,设置返回值

wait()

等待结束,设置返回值

communicate()

参数是标准输入,返回标准输出和标准出错

send_signal()

发送信号 (主要在unix下有用)

terminate()

终止进程,unix对应的SIGTERM信号,windows下调用api函数TerminateProcess()

kill()

杀死进程(unix对应SIGKILL信号),windows下同上

stdin
stdout
stderr

参数中指定PIPE时,有用

pid

进程id

returncode

进程返回值

参考

 

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

0 0
原创粉丝点击