你所需要的是一些符合
主.py):
from subprocess import Popen, PIPE, STDOUTx = Popen(['some_child.exe', 'parameter'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)while x.poll() is None: child_output = x.stdout.readline() print(child_output) if b'Do you want to send the argument?' in child_output: x.stdin.write(b'yesn') x.stdin.flush()x.stdout.close()x.stdin.close()
You’re assuming
child.exe(in your mockup demo,
python.exe) is
communicating with
main.pyvia
sys.stdin/stdout, however these I/O’s are
used to communicate with the shell that spawned the process.
很像childs的“stdout/stdin”将与
产生了这个过程,在本例中是“Popen()”。
每个派生的子进程
子流程.Popen(…)将与
它有自己的“stdout/stdin/stderr”,否则每个子进程都会产生巨大的
你的主要进程的混乱。这意味着你必须检查
在该特定子进程上输出并相应地写入,如中所做
上面的例子。
一种看待它的方式是:![输入图像描述]
[这里](https://i.stack.imgur.com/L2QWa.png)
你要开始了
主.py,并通过
系统标准输出以及
标准输入. 中的每个
input()``主.py将输出某些内容到
系统标准输出
这样你就可以读了。
同样的逻辑也适用于
子.exewhere every
input()将
输出一些东西到它的
系统标准输出但请记住-
sys不是共享的
过程间的变量)。
import sysif sys.argv[1] == 'start': inp = input('Do you want to send the argument?n').lower() if inp == 'no': sys.exit() elif inp == 'yes': #Somehow send '1' to the stdin of 1.py while it is running sys.stdout.write('1') sys.stdout.flush()但是一个简单的’print(1)
也会这样做,因为它基本上是输出的“1”到系统标准输出`为了你。
编辑2018:不要忘记关闭输入和输出,因为它们可能会离开
打开文件系统描述符
晚年的问题。
其他信息传递者
假设您控制了要
子.exe你可以修改
无论如何,其他一些选项包括:
套接字—使用常规套接字进行通信,在nix上,最有效的是Unix套接字。
更小心的尾巴!
.readline()
将假定数据中的某个地方有一个n
,很可能在末尾。我切换到.readline()
有两个原因,.read()
将挂起并等待’EOF’,除非您指定要读取的字节数(如果我不骑自行车的话)。为了能够阅读你需要合并的各种输出选择。选择()在你的代码中-或者在某种类型的缓冲区中,你调用x。标准读取(1)
一次读一个字节。因为如果您尝试读取.read(1024)
并且缓冲区中没有1024个字节,那么您的读取将挂起,直到有1024个字符为止。
我在你的房间里留了个虫子
儿童.py专门编写代码(我的作品)-这是一个简单的基本Python-希望这是一个如何调试错误的学习经验(你提到你不擅长它,这是一个学习的方法)。



