Exit with a status code
Write a Python program that exits with code 1 on failure and show the code the caller sees.
['check.py', 'x'] -> 0 ok ['check.py'] -> 1 missing argument
Approach
sys.exit(1); the parent readsreturncode.
Solution
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())['check.py', 'x'] -> 0 ok ['check.py'] -> 1 missing argument
Learn the concept
New to this topic? Read the lesson, then come back.