Windows下Python调用可执行文件传入文本输入时程序冻结求助
嘿,我来帮你搞定这个Windows下subprocess调用exe冻结的问题~
首先,先排查几个常见的坑,毕竟Windows和Linux的subprocess行为确实有不少差异:
1. 先确认你的exe路径是否正确
你写的r'C:\Users\Desktop\Python_files\file.exe'这里大概率有问题——Users后面必须跟着你的实际用户名,比如C:\Users\张三\Desktop\Python_files\file.exe或者C:\Users\John\Desktop...。很多人容易漏写用户名,导致程序找不到exe,虽然不一定直接导致冻结,但先验证路径是否存在:
import os exe_path = r'C:\Users\你的用户名\Desktop\Python_files\file.exe' print(os.path.exists(exe_path)) # 输出True才是正确路径
2. 最可能的原因:stderr缓冲区满了导致挂起
Windows下的控制台程序如果往stderr输出内容,但你的代码没有处理stderr的话,当stderr的缓冲区被填满时,进程会卡住等待读取,直接导致你的Python程序冻结。解决方法很简单,把stderr重定向到stdout或者结果文件里:
修改后的代码示例
import subprocess # 替换成你正确的exe路径 exe_path = r'C:\Users\你的用户名\Desktop\Python_files\file.exe' for filename in ['inp1.txt', 'inp2.txt']: with open(filename, 'r', encoding='utf-8') as infile, open(f'result_{filename}', 'w', encoding='utf-8') as outfile: result = subprocess.run( [exe_path], stdin=infile, stdout=outfile, stderr=subprocess.STDOUT, # 把错误输出合并到结果文件 text=True, # 用文本模式处理,避免编码/二进制转换问题 check=False # 不需要强制检查返回码,根据你的需求调整 )
3. 额外的调试技巧
如果上面的方法还不行,试试手动在CMD里运行exe,看是否正常:
cd C:\Users\你的用户名\Desktop\Python_files file.exe < inp1.txt > result_inp1.txt
如果手动运行也冻结,那问题出在file.exe本身,比如它需要交互式输入或者依赖其他文件;如果手动正常,那可以试试给subprocess加Windows特定的创建标志:
result = subprocess.run( [exe_path], stdin=infile, stdout=outfile, stderr=subprocess.STDOUT, text=True, creationflags=subprocess.CREATE_NO_WINDOW # 避免弹出控制台窗口,同时解决部分交互问题 )
这些方法应该能解决大部分Windows下subprocess冻结的问题,你先试试路径和stderr重定向的方案,大概率能搞定~
内容的提问来源于stack exchange,提问作者Pyth_newuser
相关产品推荐
相关产品推荐

