如何在Windows系统中用Python与外部命令行程序交互?
Python 与命令行程序持续交互实现示例
方法一:使用 subprocess 库
适合无需复杂提示符匹配的场景,需手动处理输入输出时机与缓冲问题。
import subprocess def interact_with_program(program_path): # 启动目标程序,开启管道并启用文本模式 proc = subprocess.Popen( [program_path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, # 启用行缓冲,保证实时读取输出 universal_newlines=True ) try: while True: # 逐行读取程序输出 output_line = proc.stdout.readline() if not output_line: # 程序结束,读取剩余错误输出 err_output = proc.stderr.read() if err_output: print(f"错误输出: {err_output.strip()}") break print(f"程序输出: {output_line.strip()}") # 根据程序实际提示判断是否需要输入(替换为你的程序提示符) if "请输入" in output_line: user_input = input("输入内容: ") proc.stdin.write(user_input + "\n") proc.stdin.flush() # 强制刷新缓冲区,确保输入被程序接收 return_code = proc.wait() print(f"程序退出,返回码: {return_code}") except Exception as e: print(f"交互出错: {str(e)}") proc.terminate() proc.wait() # 调用示例,替换为你的程序路径 if __name__ == "__main__": interact_with_program("program.exe")
关键注意点
bufsize=1避免输出积压,保证实时读取text=True以文本模式处理管道,无需手动编解码- 必须调用
stdin.flush(),否则输入可能滞留在缓冲区 - 需将判断条件中的"请输入"替换为程序实际的输入提示文本
方法二:使用 pexpect 库
专为交互式场景设计,支持自动等待特定提示符,无需手动处理循环读取逻辑。
先安装依赖:
pip install pexpect
示例代码:
import pexpect def interact_with_program_pexpect(program_path): try: # 启动程序,指定编码 child = pexpect.spawn(program_path, encoding='utf-8') while True: # 等待目标提示符、程序结束或超时 index = child.expect([r'请输入', pexpect.EOF, pexpect.TIMEOUT], timeout=30) if index == 0: # 匹配到输入提示符,打印当前输出 print(f"程序输出: {child.before.strip()}") user_input = input("输入内容: ") child.sendline(user_input) # 自动添加换行符,适配多数程序输入逻辑 elif index == 1: # 程序结束,打印剩余输出 print(f"程序结束,最后输出: {child.before.strip()}") break elif index == 2: # 超时处理 print(f"超时未收到预期提示符,当前输出: {child.before.strip()}") child.terminate() break return_code = child.wait() print(f"程序返回码: {return_code}") except Exception as e: print(f"交互出错: {str(e)}") if 'child' in locals(): child.terminate() child.wait() # 调用示例 if __name__ == "__main__": interact_with_program_pexpect("program.exe")
关键注意点
pexpect.expect()可同时匹配多个模式,返回匹配索引sendline()自动添加换行符,符合命令行程序输入习惯- 可调整
timeout参数适配程序运行时长 - 正则表达式匹配提示符时,需与程序实际输出文本完全匹配(注意标点、空格)
内容的提问来源于stack exchange,提问作者Rayamon
相关产品推荐
相关产品推荐

