【问题标题】:How can I surpass "Press any key to continue ..." in python?如何在 python 中超越“按任意键继续...”?
【发布时间】:2013-09-12 13:17:15
【问题描述】:

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

os.system("testfile.bat")

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

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

【问题讨论】:

  • 'testfile.bat' 末尾有pause 吗?
  • pause 给出“按任意键继续...”提示。只需从批处理文件中删除pause

标签: python batch-file subprocess


【解决方案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

你应该完成了。

【讨论】:

  • 假设testfile.bat 没有任何其他读取标准输入的程序。 OP 并没有说 testfile.bat 是非交互式的。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-11-10
      • 2015-01-23
      • 2010-11-29
      • 2011-12-13
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多