使用 Python 通过 STDIN/STDOUT 启动和控制外部进程 [英] Starting and Controlling an External Process via STDIN/STDOUT with Python

查看:36
本文介绍了使用 Python 通过 STDIN/STDOUT 启动和控制外部进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要启动一个外部进程,该进程将通过 stdin 和 stdout 来回发送的消息进行控制.使用 subprocess.Popen 我能够启动该过程,但无法根据需要通过 stdin 控制执行.

I need to launch an external process that is to be controlled via messages sent back and forth via stdin and stdout. Using subprocess.Popen I am able to start the process but am unable to control the execution via stdin as I need to.

我试图完成的流程是:

  1. 启动外部进程
  2. 迭代一些步骤
  1. 通过向其标准输入写入换行符,告诉外部进程完成下一个处理步骤
  2. 等待外部进程通过向其标准输出写入换行符来表示它已完成该步骤

  • 关闭外部进程的 stdin 以向外部进程表明执行已完成.
  • 到目前为止,我想出了以下几点:

    I have come up with the following so far:

    process = subprocess.Popen([PathToProcess], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    for i in xrange(StepsToComplete):
        print "Forcing step # %s" % i
        process.communicate(input='\n')
    

    当我运行上面的代码时,'\n' 没有传达给外部进程,我永远不会超过第 0 步.代码在 process.communicate() 处阻塞,不再继续.我错误地使用了communication() 方法?

    When I run the above code the '\n' is not communicated to the external process, and I never get beyond step #0. The code blocks at process.communicate() and does not proceed any further. I am using the communicate() method incorrectly?

    另外,我将如何实现等到外部进程写入新行"功能?

    Also how would I implement the "wait until the external process writes a new line" piece of functionality?

    推荐答案

    process.communicate(input='\n') 是错误的.如果您会从 Python 文档中注意到,它会将您的字符串写入孩子的标准输入,然后读取孩子的所有输出,直到孩子退出.来自 doc.python.org:

    process.communicate(input='\n') is wrong. If you will notice from the Python docs, it writes your string to the stdin of the child, then reads all output from the child until the child exits. From doc.python.org:

    Popen.communicate(input=None) 互动with process:将数据发送到标准输入.读来自 stdout 和 stderr 的数据,直到到达文件尾.等待进程终止.可选的输入参数应该是一个字符串被发送到子进程,或无,如果没有数据应该发送到孩子.

    Popen.communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

    相反,您只想写入孩子的标准输入.然后在循环中读取它.

    Instead, you want to just write to the stdin of the child. Then read from it in your loop.

    更像是:

    process=subprocess.Popen([PathToProcess],stdin=subprocess.PIPE,stdout=subprocess.PIPE);
    for i in xrange(StepsToComplete):
        print "Forcing step # %s"%i
        process.stdin.write("\n")
        result=process.stdout.readline()
    

    这会做一些更像你想要的事情.

    This will do something more like what you want.

    这篇关于使用 Python 通过 STDIN/STDOUT 启动和控制外部进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆