2

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?

4

1 回答 1

2

您可以在 Python 脚本中添加一个选项--pause,并且仅在设置了该选项时才提示按键:

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

不过,这需要修改所有脚本。另一种选择可能是使用这样的批处理脚本来运行您的 Python 脚本:

@echo off

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

像这样使用它:

pyrunner.cmd script.py {options}
于 2013-07-01T10:43:31.517 回答