[Tutor] Ending a script

Chris Fuller cfuller084 at thinkingplanet.net
Wed Feb 6 18:14:16 CET 2008

On Wednesday 06 February 2008 09:23, Damian Archer wrote:
> When I am running a script in cmd the script runs but the cmd windows
> closes immediately after the script has finished.
> Is there anyway I can freeze the cmd window until a user actually closers
> it??

There are numerous ways to do this, the simplest (and least interesting) being 
to use raw_input() to prompt the user to hit ENTER.

A more elegant way would be to redirect the text somewhere else, perhaps a GUI 
textbox, or even out a network socket to an independent logging process.  
This is simple to do in python.  All you need is a class with a write() 
method.  Asign sys.stdout and sys.stderr to an instance of such a class.  You 
can use the same instance, or treat them seperately.

When the interpreter prints some output, or an exception is raised, the output 
will be passed to the write() methods of these objects, and your code can 
perform any arbitrary manipulations upon the output that is desired.

Handling exceptions is actually a bit trickier, of course, since the default 
action is to terminate the program (although not always if it occurs in a GUI 
callback), but there are other uses for sys.stderr.  A lot of modules will 
display error or warning messages on it, for instance. 

There is a bigger caveat:  these do not correspond to the stdout and stderr 
used by the OS and the underlying C inside the interpreter.  Many python 
modules wrap C libraries (pygtk, for instance), and the messages displayed at 
runtime will not be handled with any python-awareness.  You can still 
redirect these, but you have to make low-level operating system calls, and 
the details differ ever so slightly from standard POSIX systems if you are 
suffering under the yoke of Redmond.

The attached program demostrates these concepts, except the nasty lowlevel OS 
dependent bit.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: redirtk.py
Type: application/x-python
Size: 1398 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20080206/52548809/attachment-0001.bin 

More information about the Tutor mailing list