Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

cmd - Run python.exe and pause after the script has executed

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?

question from:https://stackoverflow.com/questions/65837250/py-file-immediately-closes-when-executed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...