使用subprocess.run调用带“Press any key to exit”提示的Windows第三方控制台程序时的报错解决求助
subprocess.run调用带“Press any key to exit”提示的Windows第三方控制台程序时的报错解决求助
我有一个第三方提供的Windows控制台可执行文件,它是一个文件转换器,需要指定输入和输出文件。转换完成后会弹出“Press any key to exit”的提示。我尝试在自己的Python程序里用subprocess.run来调用它,虽然转换功能能正常工作,但会出现这个提示以及一个未处理的异常错误。
我的代码如下:
def load_mydata(self, file): _output = file.with_suffix(".csv") # delete output file if it already exists _output.unlink(missing_ok=True) _args = 'MyDataConverter.exe input="{}" output="{}"'.format(file, _output) print(_args) subprocess.run(_args) print('tada')
运行后,在两次print语句的输出之间会出现以下内容:
Press any key to exit. Unhandled Exception: System.InvalidOperationException: Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read. at System.Console.ReadKey(Boolean intercept) at Converter.Program.ProgramExit(TextWriter output, Int32 returnValue) at Converter.Program.Main(String[] args)
我已经尝试了几种方法,但都没有解决问题:
- 尝试通过
input参数传入换行符,模拟按下任意键:
subprocess.run(_args, input=b'\n')
- 尝试用文件作为标准输入:先创建了
MyResponsefile.txt(文件内容仅包含一个字符和换行符),然后执行:
with open('MyResponsefile.txt', 'r') as fIn: subprocess.run(_args, stdin=fIn)
- 甚至尝试捕获所有异常并忽略:
try: subprocess.run(_args) except: pass
但每次尝试的结果都完全一样,还是会出现那个“Press any key to exit”提示和对应的异常错误。有没有办法解决这个问题呢?
备注:内容来源于stack exchange,提问作者marcp
相关产品推荐
相关产品推荐

