On 13Mar2023 10:18, scruel tao <scru...@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 <c...@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list