转发: How to exit program with custom code and custom message?

Cameron Simpson cs at cskk.id.au
Mon Mar 13 16:35:48 EDT 2023


On 13Mar2023 10:18, scruel tao <scruelt at hotmail.com> wrote:
>Chris:
>> but for anything more complicated, just print and then exit.
>> It's worth noting, by the way, that sys.exit("error message") will
>> print that to STDERR, not to STDOUT, which mean that the equivalent
>> is:
>
>Yes, I know, but don’t you think if `sys.exit` can take more parameters 
>and have a default output channel selection strategy will be better?

That kind of thing is an open ended can of worms. You're better off 
writing your own `aort()` function such as:

     def abort(message, *a, output=None, exit_code=1):
         if a:
             message = message %a
         if output is None:
             output = sys.stderr
         print(message, file=output)
         exit(exit_code)

which can be extended with whatever (potentially _many_) custom options 
you like. `sys.exit()` itself is just to abort your programme, and 
doesn't want a lot of knobs. The more knobs, the more things which have 
to be implemented, and if the knobs are not independent that gets 
complicated very quickly. Not to mention agreeing on what knobs to 
provide.

BTW, `sys.exit()` actually raises a `SystemExit` exception which is 
handled by the `sys.excepthook` callback which handles any exception 
which escapes from the programme uncaught.

Finally, in larger programs it is uncommon to call `sys.exit()` except 
in the very outermost "main function", and even there I tend to just 
`return`, myself. Example:

     def main(argv=None):
         if argv is None:
             argv = sys.argv
         xit = 0
         .... handle the command line arguments, run code ...
         ... errors set xit=1 or maybe xit="message" ...
         return xit

     if __name__ == '__main__':
         sys.exit(main(sys.argv))

Notice that the only call to `sys.exit()` is right at the bottom.  
Everything else is just regularfunction returns.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list