【问题标题】:How to read stream of a subprocess in python?如何在python中读取子进程的流?
【发布时间】:2017-02-07 10:36:11
【问题描述】:

我用subprocess.Popen 创建了一个进程并得到它的stdout。 我想从stdout 读取内容并在另一个线程中打印出来。 由于我的目的是稍后制作一个交互式程序,所以我不能使用subprocess.communicate

我的基本要求是:一旦子进程输出一些东西,线程应该立即将它打印到屏幕上。

这里是代码

import subprocess
import thread
import time

def helper(s):
    print "start",time.gmtime()
    while True:
        print "here"
        print s.next()
    print "finished",time.gmtime()
    thread.start_new_thread(helper,(out_stream,))

def process_main():
    global stdin_main
    global stdout_main
    p = subprocess.Popen("/bin/bash", shell=False, stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT, bufsize=0)
    stdin_main = p.stdin
    stdout_main = p.stdout
    th1 = thread_print_stream(stdout_main)
    stdin_main.write("ls -la\n")
    stdin_main.flush()
    time.sleep(30)

    p.terminate()

process_main()

“开始”和“完成”之间的时间间隔应该非常快。但是,它是 30 秒,与进程终止前的时间完全相同。 我不明白为什么输出不是实例。 或者我怎样才能使其实例化?

【问题讨论】:

  • 您可能正在遭受缓冲。这可能会有所帮助:stackoverflow.com/questions/1183643/…
  • @cdarke 患有子进程或文件?我设置了 bufsize=0。
  • 您是否阅读了链接中接受的答案?
  • @cdarke 是的。尽管我确实在该线程中找到了答案,但它与该正确答案无关。我已经发布了这个问题的答案。谢谢

标签: python multithreading subprocess


【解决方案1】:

正如 cdarke 所说。该程序受到缓冲的影响。 然而,它更像是 python 2.x 中的一个错误。 当前程序中的逻辑没有错。

要解决此问题,您必须重新打开标准输出。 就像下面的代码:

def thread_print_stream(out_stream):
  def helper(s):
    print "start",time.gmtime()
    for line in io.open(out_stream.fileno()):
      print line
    print "finished",time.gmtime()
  thread.start_new_thread(helper,(out_stream,))

并添加

stdin_main.close()
stdout_main.close()

在子进程终止之前,确保不会出现错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-26
    • 2010-10-27
    • 2012-04-06
    • 1970-01-01
    • 2016-03-26
    • 2015-12-27
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多