How to exit program with custom code and custom message?

Chris Angelico rosuav at gmail.com
Mon Mar 13 05:27:19 EDT 2023


On Mon, 13 Mar 2023 at 20:00, scruel tao <scruelt at hotmail.com> wrote:
>
> Currently, I use `sys.exit([arg])` for exiting program and it works fine.
> As described in the document:
> > If another type of object is passed, None is equivalent to passing zero, and any other object is printed to stderr and results in an exit code of 1.
>
> However, if I want to exit the program with status 0 (or any numbers else except 1) and print necessary messages before exiting, I have to write:
> ```python
> print("message")
> sys.exit()
> ```
> So why `sys.exit` takes a list of arguments (`[arg]`) as its parameter? Rather than something like `sys.exit(code:int=0, msg:str=None)`?

It doesn't actually take a list of arguments; the square brackets
indicate that arg is optional here. So you can either quickly print
out an error message and exit, or you can exit with any return code
you like, 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:

print("error message", file=sys.stderr)
sys.exit(1)

Which is another reason to do things differently on success; if you're
returning 0, you most likely want your output on STDOUT.

ChrisA


More information about the Python-list mailing list