【问题标题】:Python subprocess another python script not producing outputPython子处理另一个不产生输出的python脚本
【发布时间】:2018-06-22 16:45:13
【问题描述】:

我有一个简单的python3脚本test.py

print('Test')

while True:
    inp = input('> ')
    print(input)

当我尝试使用 subprocess.Popen 运行它并获取它的输出时,它会冻结:

from subprocess import Popen, PIPE
p = Popen(['python3', 'test.py'], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)
print(p.stdout.read())

所以,我没有从该脚本获得任何输出。我尝试使用 communicate 并不知何故奏效了:

p.communicate()[0]

但我仍然需要使管道标准输出工作。从我的脚本获取输出的第一个示例有什么问题?

UPD: communicate 显示test.py 中有一个异常:EOF on input on line 4。为什么?如何与此类脚本交互?

【问题讨论】:

    标签: python-3.x subprocess output


    【解决方案1】:

    您没有向标准输入提供任何输入,因此您自然会在第 4 行得到一个EOFError,这是input 到达 EOF 时引发的异常。但即使你给它一些输入,因为它有一个无限循环,它最终会消耗所有输入并最终提高EOFError。您应该捕获异常并优雅地结束脚本。

    另外,您在第 5 行有一个错字,您希望它打印inp,而不是input

    最后,您应该始终使用communicate,而不是直接从stdout 读取或直接写入stdin

    来自Popen's documentation

    警告:使用communicate() 而不是.stdin.write.stdout.read.stderr.read 以避免由于任何其他操作系统管道缓冲区填满并阻塞子进程而导致的死锁。

    已更正test.py:

    print('Test')
    
    while True:
        try:
            inp = input('> ')
        except EOFError:
            print 'Done'
            break
        print(inp)
    

    test.py互动的正确方式:

    >>> from subprocess import Popen, PIPE
    >>> p = Popen(['python', 'test.py'], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)
    >>> p.communicate('hello\nworld\n')
    ('Test\n> hello\n> world\n> Done\n', '')
    >>> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 2020-07-03
      相关资源
      最近更新 更多