Exit with a status code

Easysys Module Programs · 3 of 20

Write a Python program that exits with code 1 on failure and show the code the caller sees.

Advertisement
Output
['check.py', 'x'] -> 0 ok
['check.py'] -> 1 missing argument

Approach

  1. sys.exit(1); the parent reads returncode.

Solution

Python
import subprocessimport sys with open("check.py", "w") as f:    f.write("import sys\nif len(sys.argv) < 2:\n    print('missing argument', file=sys.stderr)\n    sys.exit(1)\nprint('ok')\n")for args in [["check.py", "x"], ["check.py"]]:    r = subprocess.run([sys.executable, *args], capture_output=True, text=True)    print(args, "->", r.returncode, (r.stdout or r.stderr).strip())
Output
['check.py', 'x'] -> 0 ok
['check.py'] -> 1 missing argument
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More sys module programs

← All 20 sys Module Programs