简体   繁体   English

在Python中使用子流程时,如何从主流程中获取用户输入

[英]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.

相关问题 如何使用python从浏览器获取用户输入 - How I can get user input from browser using python 使用python`subprocess`时,如何在参数中使用进程号? - When using python `subprocess`, how can I use process number in arguments? python multiprocessing:如何从子进程修改在主进程中创建的字典? - python multiprocessing: How to modify a dictionary created in the main process from a subprocess? 如何将 2 个输入写入 python 子进程 - How can I write 2 input to python subprocess 从用户获取输入然后使用子流程启动流程 - Getting input from user then starting a process with subprocess 我如何确定用户何时在输入某些内容作为Python的输入? - How can I determine when a user is in the process of entering something as an input in Python? 如何使用带有Mutliprocessing的PYTHON打开程序,并从主进程发送它的字符串? - How can I open a program using PYTHON with Mutliprocessing, and send it strings from the main process? 如何终止使用 python 子进程启动的远程进程? - How can I terminate a remote process that I launched with a python subprocess? 当使用 popen 运行或在子进程库中运行时,如何在自己的行上打印 python 中的输入提示? - How can I print an input prompt in python on its own line when ran using popen or run in the subprocess library? 当需要用户输入/确认时如何暂停其他进程子进程 Python - How do I pause other processes when user input / confirmation is required Subprocess Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM