zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    ubuntu 修改默认root及密码
    两种方法解决tomcat的 Failed to initialize end point associated with ProtocolHandler ["http-apr-8080"]
    关于小米驱动程序的问题
    ubuntu下搭建lamp
    cocos2dx在ubuntu下配置声音引擎
    cocos2dx 帧动画的两种创建方式
    c++ 访问者模式(visitor pattern)
    c++ 职责链模式(Chain of Responsibility)
    c++ 状态模式(state)
    创建镜像推送至仓库
  • 原文地址:https://www.cnblogs.com/catmelo/p/2941711.html
Copyright © 2011-2022 走看看