Python子进程:来回传递多个输入/输出

2024-04-23 22:55:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用子进程.Popen允许两个Python程序进行或多或少的对话。我希望能够从父级向子级发送输入,接收子级的响应,然后基于该响应发送一个新的输入。子流程.通信()在一次I/O交互后关闭进程。是否可以为多个I/O打开同一个子进程?目前,我的代码挂起。在

父代码:

from __future__ import print_function
import subprocess
import sys


try:
     p = subprocess.Popen(['python','childprocess.py'],
                          stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE,
                          bufsize=1,
                          universal_newlines=True)
except Exception as e:
     print("Error: "+str(e))
     sys.exit(-1)

p.stdin.write('This is the first input\n')
p.stdin.flush()
print(p.stdout.readline())
p.stdin.write('This is the second input\n')
print(p.stdout.readline())

子代码:

^{pr2}$

在这种情况下,我可以只给出两个输入,然后读取两个输出,但是如果我希望能够使用子输出来通知父输入(例如,一个数字猜测者),那么我可以用子进程来完成吗?在


Tags: the代码import进程isstdinstdoutsys