views:

2140

answers:

6
+3  Q: 

Pause in Python

I am running commandline python scripts from the Windows taskbar by having a shortcut pointing to the python interpreter with the actual script as 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 suboptimal because it requires pressing the return key (instead of any key).

Any ideas?

+2  A: 

In Windows, you can use the msvcrt module.

msvcrt.kbhit() Return true if a keypress is waiting to be read.

msvcrt.getch() Read a keypress and return the resulting character. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed.

If you want it to also work on Unix-like systems you can try this solution using the termios and fcntl modules.

dF
+7  A: 

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.

David Grant
This doesn't help in the case specified by Bernd: starting a script from a taskbar shortcut, unless the shortcut is properly configures (which is not the default case).
bgbg
@bgbg: but the whole idea is that the shortcut is changed
David Grant
/K requires to terminate cmd via "exit" or closing the window using the mouse. That's a bit more than a single keypress :-)
@Bernd: True, but you can use Alt + Space + C, and it prevents you from having to rewrite all your scripts!
David Grant
+5  A: 

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

regan
A: 

An external WConio module can help here: http://newcenturycomputers.net/projects/wconio.html

import WConio
WConio.getch()
RommeDeSerieux
+3  A: 

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>
bgbg
+1: Many people can find the "Enter" or "Return" key without making large mistakes. Demanding "any key" instead of return seems a bit silly.
S.Lott
A: 
import pdb
pdb.debug()

This is used to debug the script. Should be useful to break also.

Lakshman Prasad