I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.

After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.

What is the most straightforward way to keep the interpreter window open until any key is pressed?

In batch files, one can end the script with pause. The closest thing to this I found in python is raw_input() which is sub-optimal because it requires pressing the return key (instead of any key).


Solution 1:

One way is to leave a raw_input() at the end so the script waits for you to press Enter before it terminates.

Solution 2:

Try os.system("pause") — I used it and it worked for me.

Make sure to include import os at the top of your script.

Solution 3:

There's no need to wait for input before closing, just change your command like so:

cmd /K python <script>

The /K switch will execute the command that follows, but leave the command interpreter window open, in contrast to /C, which executes and then closes.

Solution 4:

The best option: os.system('pause') <-- this will actually display a message saying 'press any key to continue' whereas adding just raw_input('') will print no message, just the cursor will be available.

not related to answer:

os.system("some cmd command") is a really great command as the command can execute any batch file/cmd commands.

Solution 5:

One way is to leave a raw_input() at the end so the script waits for you to press enter before it terminates.

The advantage of using raw_input() instead of msvcrt.* stuff is that the former is a part of standard Python (i.e. absolutely cross-platform). This also means that the script window will be alive after double-clicking on the script file icon, without the need to do

cmd /K python <script>