python, subprocess: reading output from subprocess

前端 未结 6 1412
暗喜
暗喜 2020-12-09 18:57

I have following script:

#!/usr/bin/python

while True:
    x = raw_input()
    print x[::-1]

I am calling it from ipython:

6条回答
  •  借酒劲吻你
    2020-12-09 19:09

    Use communicate() instead of .stdout.read().

    Example:

    from subprocess import Popen, PIPE
    p = Popen('./script.py', stdin=PIPE, stdout=PIPE, stderr=PIPE)
    input = 'abc\n'
    stdout, stderr = p.communicate(input)
    

    This recommendation comes from the Popen objects section in the subprocess documentation:

    Warning: Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

提交回复
热议问题