sys.exit()

Donn Cave donn at drizzle.com
Sat Oct 11 00:52:52 EDT 2003


Quoth Duncan Booth <duncan at NOSPAMrcp.co.uk>:
| "Donn Cave" <donn at drizzle.com> wrote in news:1065757907.371391 at yasure:
...
|> 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.

That's right, it does work and it is easier.  But please don't think
of print >> sys.stderr as something that's hard, lest that lead to
code like distutils that just neglects to do it.

distutils perhaps has the excuse that it had this problem before there
was a solution, but it's a good example of the problem.  It's natural
to want to save the output of distutils to disk - I think it's really a
good practice to do this routinely so later you know how an application
was built, what went into it and where it got installed.  In this case,
you'd always redirect both stdout and stderr, with a shell command line
like 'python setup.py > make.log 2>&1', so it would seem that the choice
between stdout and stderr would not matter.  But it matters a lot, because
when stdout is a disk file, it's block buffered.  That means the actual
flush to disk may be deferred for some time.  Meanwhile, the applications
and processes that distutils invokes (cc, etc.) write immediately to disk
because if nothing else their output buffers flush when they exit.  So
your log file starts with a bunch of diagnostic output from cc, and only
later gets to the distutils output that announces it's going to run cc.
Completely unreadable.  stderr is always line buffered.

	Donn Cave, donn at drizzle.com




More information about the Python-list mailing list