【发布时间】:2016-01-23 15:39:54
【问题描述】:
感谢您花时间回答问题。我正在玩 Python 3.4,我有两个简单的 Python 程序。一,一个名为 test.py 的程序,它接受用户输入并打印一些东西。
while True:
print("enter something...")
x = input()
print(x)
time.sleep(1)
为了向这个程序发送输入,我有另一个使用子进程的程序:
from subprocess import Popen, PIPE
cat = Popen('python test.py', shell=True, stdin=PIPE, stdout=PIPE)
cat.stdin.write("hello, world!\n")
cat.stdin.flush()
print(cat.stdout.readline())
cat.stdin.write("and another line\n")
cat.stdin.flush()
print(cat.stdout.readline())
但是当我运行上面的程序时,我得到一个错误:
enter something...
hello, world!
Traceback (most recent call last):
File "/opt/test.py", line 9, in <module>
x = input()
EOFError: EOF when reading a line
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe
如果我将 test.py 替换为像“cat”这样的标准 linux 命令,一切都会按预期工作。
有什么方法可以发送多个标准输入并读取多个标准输出?
【问题讨论】:
-
我认为你错过了 Popen
Popen(['python', 'test.py'], shell=True, stdin=PIPE, stdout=PIPE)上的命令 python -
错别字,如果您看到第一次打印成功,程序实际上会运行。
-
如果您使用 Python 3,
cat.stdin.write("hello, world!\n")应该会引发错误(启用文本模式需要universal_newlines=True)因此您的实际代码不同或者您没有使用 Python 3。
标签: python python-3.x pipe subprocess