4.3. Syntax Exit Code — Python
exit code
0- no errorany 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
4.3.1. Exit Code 0
File myfile.py:
Let's run the script:
And now check the exit code:
4.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:
Exit Code 1 means that there was an error during script execution.
4.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!')
4.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 myfile.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 myfile.py ********************************************************************** File "/home/myuser/myfile.py", line 41, in myfile Failed example: 1 + 2 Expected: 3 Got: 4 ********************************************************************** 1 items had failures: 1 of 2 in myfile ***Test Failed*** 1 failures. $ echo $? 1