3.3. Syntax Exit Code

  • exit code 0 - no error

  • any other exit status - error

  • This will not work in Jupyter

>>> try:
...     float('hello')
... except ValueError:
...     print('Cannot type cast to float')
...     exit(1)
Traceback (most recent call last):
SystemExit: 1

3.3.1. Exit Code 0

File myfile.py:

print('ok')

Let's run the script:

$ python myfile.py
ok

And now check the exit code:

$ echo $?
0

3.3.2. Exit Code 1

File myfile.py:

raise RuntimeError('error')

Let's run the script:

$ python myfile.py
Traceback (most recent call last):
  File "myfile.py", line 1, in <module>
    raise RuntimeError('error')
RuntimeError: error

And now check the exit code:

$ echo $?
1

Exit Code 1 means that there was an error during script execution.

3.3.3. Exit Codes from Python

import sys

try:
    float('hello')
except ValueError:
    print('Cannot type cast to float')
    sys.exit(1)

print('Hello World!')

3.3.4. Use Case - 1

  • Tests

  • CI/CD - Continuous Integration / Continuous Delivery

When all tests pass (without any error) exit code will be zero. This is how CI/CD tools works. They check what exit status was generated while executing particular steps of the CI/CD pipeline.

$ python -m doctest myscript.py
$ echo $?
0

In case of error the exit code will be non-zero. This is why CI/CD tool knows if tests failed, therefore it yields an error for whole build or pipeline execution.

$ python -m doctest myscript.py
**********************************************************************
File "/home/watney/myscript.py", line 41, in myscript
Failed example:
    1 + 2
Expected:
    3
Got:
    4
**********************************************************************
1 items had failures:
   1 of   2 in myscript
***Test Failed*** 1 failures.

$ echo $?
1