[Tutor] Logging exceptions, but getting stderr output instead

Steven D'Aprano steve at pearwood.info
Sun May 29 22:33:06 EDT 2016


On Wed, May 25, 2016 at 03:44:28PM -0400, Alex Hall wrote:
> You're not missing anything; I wasn't clear. I wasn't sure if raise or
> sys.exit(1) were the preferred ways, or if there was some other way I
> didn't know about. I've never had to force a script to halt before, at
> least not one I mean to schedule to run on its own once a day, so wanted to
> check that those are indeed the recommended ways.

raise and sys.exit() do different things, which both happen to result in 
the script halting.

`raise` re-raises the current exception, that's all. What happens from 
that point depends: the exception could be caught by another 
try...except handler, or it might not be. If it isn't caught by 
anything, the interpreter will print a traceback and error message, and 
then halt with a non-zero exit code.

`sys.exit` will exit. Technically it actually raises an exception, 
SystemExit, which can also be caught like any other exception, but 
normally it won't be. (I can go into detail about exactly when it 
will be caught if you like.) If you call sys.exit with no argument, or 
with argument 0, then it will halt the script with exit code 0 
("success") and no traceback. Any other integer code will set the exit 
code to that value, and any string value will print that string to 
stderr and then exit with a non-zero exit code.


-- 
Steve


More information about the Tutor mailing list