Python中subprocess需要用户输入确认时如何暂停其他进程
多子进程交互输入与进程暂停实现方案
问题根因
你当前遇到的问题是三个子进程共享同一个终端标准输入/输出流,输入信号会被随机分配给子进程,同时A、C的运行输出也会覆盖B的交互提示,导致无法正常完成输入。
推荐实现方案(跨平台兼容Windows/macOS/Linux)
步骤1:安装依赖
使用psutil实现跨平台的进程暂停/恢复操作:
pip install psutil
步骤2:修改B.py代码
新增标记逻辑,在需要等待用户输入前通知父进程,输入完成后清除标记,同时修正原有语法错误:
import os # 写入等待输入标记,通知父进程 with open(".b_input_flag", "w") as f: f.write("1") # 修正原有语法错误:input参数加引号,lower为方法需要加()调用 reply = input("do you want to continue this action y/n :)") if reply.lower() == 'yes' or reply.lower() == 'y': take_this_action() elif reply.lower() == 'no' or reply.lower() == 'n': take_other_action() # 输入完成后清除标记 if os.path.exists(".b_input_flag"): os.remove(".b_input_flag")
步骤3:修改run.py代码
实现标记监听、进程暂停/恢复、输入转发逻辑:
import subprocess import psutil import os import time import atexit # 注册退出清理逻辑,避免残留标记文件 def cleanup(): if os.path.exists(".b_input_flag"): os.remove(".b_input_flag") atexit.register(cleanup) # 启动子进程,单独绑定B的标准输入输出避免流冲突 p_a = subprocess.Popen(['python3', '-u', 'A.py']) p_b = subprocess.Popen( ['python3', '-u', 'B.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True ) p_c = subprocess.Popen(['python3', '-u', 'C.py']) # 封装为psutil进程对象 proc_a = psutil.Process(p_a.pid) proc_c = psutil.Process(p_c.pid) paused = False while p_b.poll() is None: # 检测到B等待输入的标记 if os.path.exists(".b_input_flag"): if not paused: # 暂停A、C进程 proc_a.suspend() proc_c.suspend() paused = True # 打印B的交互提示,转发用户输入 print(p_b.stdout.readline(), end="") user_input = input() + "\n" p_b.stdin.write(user_input) p_b.stdin.flush() else: if paused: # 恢复A、C进程运行 proc_a.resume() proc_c.resume() paused = False time.sleep(0.1) # 等待所有子进程运行结束 p_a.wait() p_c.wait() # 输出B的剩余运行日志 print(p_b.communicate()[0])
其他说明
- 如果仅在Linux/macOS环境运行,可不用安装psutil,直接用系统信号实现暂停恢复:
os.kill(pid, signal.SIGSTOP)暂停,os.kill(pid, signal.SIGCONT)恢复 - 如果不希望修改B.py代码,可使用
pexpect库匹配B的输出特征字符串,检测到交互提示后执行暂停逻辑,该方案无需修改业务代码,但匹配稳定性弱于主动标记方案
内容的提问来源于stack exchange,提问作者Randolp
相关产品推荐
相关产品推荐

