如何在python中超越“按任意键继续...”?

时间:2013-09-12 13:17:16

标签: python batch-file subprocess

在我的项目中,我从python脚本启动.bat文件。就像这样:

os.system("testfile.bat")

完成此`testfile.bat后,它会以提示符Press any key to continue ...结束。我希望我的python脚本能够超越这个提示,并以某种方式模拟按键。

我怎样才能实现这一目标?我已经通过使用子进程实现了这个功能,但事实证明,子进程不适合我的项目的上下文(与打印到控制台有关)。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

使用subprocess模块始终适合并优于os.system

只做

sp = subprocess.Popen("testfile.bat", stdin=subprocess.PIPE)
sp.stdin.write("\r\n") # send the CR/LF for pause
sp.stdin.close() # close so that it will proceed

你应该完成。

答案 1 :(得分:0)

>nul添加到暂停命令的末尾(在批处理文件中。)它将不会打印“按任意键继续。

答案 2 :(得分:0)

如果您在Bat文件末尾有“暂停”,只需删除它,它将在子进程完成后继续执行其余的python脚本。

p = subprocess.Popen("testfile.bat", shell=False, \
                          cwd=path_to_exe)

p.wait()