代码之家  ›  专栏  ›  技术社区  ›  marc

读取子进程输出python

  •  0
  • marc  · 技术社区  · 7 年前

    我正在使用“Popen”运行子进程。我需要阻塞,直到此子进程完成,然后读取其输出。

    p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, encoding="utf-8")
    p.communicate():
    output = p.stdout.readline()
    print(output)
    

    我得到一个错误

    ValueError: I/O operation on closed file.
    

    如何在子流程完成后读取输出,但我不想使用poll(),因为子流程需要时间,而且无论如何我都需要等待其完成。

    2 回复  |  直到 7 年前
        1
  •  1
  •   tripleee    7 年前

    这应该有效:

    p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, encoding="utf-8")
    output, error = p.communicate()
    
    print(output)
    if error:
        print('error:', error, file=sys.stderr)
    

    然而, subprocess.run() 现阶段首选:

    p = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    print("output:", p.stdout)
    
    if proc.stderr:
        print("error:", p.stderr, file=sys.stderr)
    
        2
  •  0
  •   Zags    7 年前

    使用 subprocess.check_output . 它返回命令的输出。