sys.exit()

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Oct 10 04:52:18 EDT 2003


"Donn Cave" <donn at drizzle.com> wrote in news:1065757907.371391 at yasure:

>| Is sys.exit() really a good choice? Is there something more elegant? (I
>| tried return but it is valid only in a function)
> 
> Your question has already been answered many times over, so I will
> instead note something about the above that is rather common but
> wrong.  "print" writes to sys.stdout (unless instructed otherwise),
> and in the present case this output should certainly go to sys.stderr.
> The easiest way to do that in recent versions of python (2.0 and
> later) is "print >> sys.stderr".

Note that the suggestions to use "sys.exit(message)" or "raise 
SystemExit(message)" will send the message to sys.stderr. This is probably 
easier than doing it explicitly in a separate print statement, plus it has 
the advantage that if you want to catch the exit for any reason you also 
catch the error message.

I've actually ended up doing this on occasion in unit tests, if you are 
testing something that should cause a fatal error its a lot easier if the 
error message is encapsulated in the SystemExit exception.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list