[英]How can I get user input from main process when using subprocess in Python
For example, program1.py call program2.py: 例如,program1.py调用program2.py:
program1.py 程式1
subprocess.Popen("program2.py", stdin=subprocess.PIPE).communicate()
program2.py program2.py
user_input = input("Yes or No?")
But when I run program1, the program2 cannot get the user input from the main process in my case. 但是,当我运行program1时,program2无法从我的主进程中获取用户输入。 It says "EOF when reading a line". 它说“读取行时的EOF”。 Could you give me some advice to get user input. 您能否给我一些建议以获取用户输入。
You are not passing any data to program2.py
. 您没有将任何数据传递给program2.py
。 I assume you are using Python 3, from the use of input
(instead of raw_input
in Python 2). 我假设您使用的是Python 3,而不是input
(而不是Python 2中的raw_input
)。 Here is how I would do it: 这是我的方法:
import subprocess
import sys
cmd = [sys.executable, 'program2.py']
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE)
proc.communicate('Y'.encode())
Passes "Y" through to the second program. 将“ Y”传递给第二个程序。 The encode()
is required in Python 3, but not Python 2. This is because Python 3 strings are multi-byte, whereas the stdin
stream uses single byte strings, like Python 2 strings. 在Python 3中需要encode()
,但在Python 2中不是必需的。这是因为Python 3字符串是多字节的,而stdin
流则使用单字节字符串,例如Python 2字符串。 No changes are required at the program2.py
end. 在program2.py
结束时不需要任何更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.