感谢你抽出时间来回答问题。我正在尝试使用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命令,则一切正常。
有没有办法发送多个stdin写入并读取多个stdout?
Popen(['python', 'test.py'], shell=True, stdin=PIPE, stdout=PIPE)
。 - Ramon Moraescat.stdin.write("hello, world!\n")
将引发错误(需要使用universal_newlines=True
来启用文本模式),因此您的实际代码可能有所不同或者您没有使用Python 3。 - jfsimport
模块并调用其函数(必要时使用multiprocessing
)而不是将其作为子进程运行。 - jfs