Run python.exe and pause after the script has executed

会有一股神秘感。 提交于 2021-02-16 14:33:09

问题


I know this has been asked couple of times, but I haven't found a good solution. I wish to run my python scripts using python.exe with possibly a command line argument or such to make the python script pause after the execution. Ideal solution would be something like python myscript.py -pause and now it'd say "Press any key to continue ..." after the execution. As far as I know this is not possible, but I'm looking for a similar solution.

The solutions I've found so far are:

  1. Running my script with cmd line: cmd /K python myscript.py but it leaves the cmd window open stupidly, I now need to write exit to get back to my text editor.
  2. Manually adding input("Press any key to continue ...") to my python scripts, but I often need to open like 25 different scripts within an hour, and it feels stupid to write it for each one of them, and then remove it once I'm done.

Is there a better solution, like automatically calling input() after script's been executed?


回答1:


You could add an option --pause to your Python scripts, and prompt for keypress only if that option is set:

import getopt
import msvcrt

opts, args = getopt.getopt(sys.argv[1:], '...', ['pause', ...])
for opt, arg in opts:
    if opt == "--pause":
        promptForKeypress = True
    ...
...
if promptForKeypress:
    msvcrt.getch()      # note: Windows-only
# End of Script

That would require modifying all your scripts, though. Another option might be using a batch script like this for running your Python scripts:

@echo off

if not "%1"=="" (
  python %*
  pause
)

Use it like this:

pyrunner.cmd script.py {options}


来源:https://stackoverflow.com/questions/17401868/run-python-exe-and-pause-after-the-script-has-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!