Skamah One
Skamah One

Reputation: 2456

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?

Upvotes: 2

Views: 1655

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200233

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}

Upvotes: 2

Related Questions