sys.stderr.write and sys.exit

GinTon jonas.esp at googlemail.com
Fri Nov 24 00:41:13 CET 2006


Thanks Ben Finney. So it's understood very well.

Ben Finney ha escrito:

> "GinTon" <jonas.esp at googlemail.com> writes:
>
> > Is the same use
>>    >>> sys.stderr.write('error message'); sys.exit(1)
> > than
>>    >>> sys.exit('error message') ?
>
> Code that wants to catch SystemExit will get a different exception
> object in each case::
>
>     >>> import sys
>     >>> from StringIO import StringIO
>     >>> sys.stderr = StringIO()
>
>     >>> try:
>     ...     sys.stderr.write('error message')
>     ...     sys.exit(1)
>     ... except SystemExit, e:
>     ...     print "stderr contains:", sys.stderr.getvalue()
>     ...     print "e.code is:", e.code
>     ...
>     stderr contains: error message
>     e.code is: 1
>
>     >>> try:
>     ...     sys.exit('error message')
>     ... except SystemExit, e:
>     ...     print "stderr contains:", sys.stderr.getvalue()
>     ...     print "e.code is:", e.code
>     ...
>     stderr contains: error message
>     e.code is: error message
>
> I quite often catch SystemExit in unit tests, or other code that is
> inspecting a program module.




More information about the Python-list mailing list