How to exit program with custom code and custom message?

scruel tao scruelt at hotmail.com
Mon Mar 13 22:34:37 EDT 2023


Lars:
> I totally understand your reasoning here, but in some way it follows the unix philosophy: Do only one thing, but do that good.

I understand, python is not strongly typed, so `sys.exit` will be able to accept any types parameters rather than just integer.
In order to handle such “other” types logic, I think this function already violated the unix philosophy, and there is no way to avoid it.

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

Thank you for your advice and example, I applied such wrappers for many years, this question comes more from “pythonic” discussion, because as I mentioned above, `sys.exit` can accept any types.

> 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.

Interesting, `raise SystemExit` seems to have the same behavior as `sys.exit`:

```shell
python -c "raise SystemExit(100)"
echo $?
<<< 100

python -c " import sys; sys.exit(100)"
echo $?
<<< 100

python -c "raise SystemExit('a’)"
<<< a
echo $?
<<< 1

python -c " import sys; sys.exit('a’)"
<<< a
echo $?
<<< 1

```

So, `sys.exit` is just a shortcut for `raise SystemExit`, or not? (Haven’t yet check the cpython source code)


More information about the Python-list mailing list