Python Practice › sys Module Programs › Program 18
Exit with a message
Write a Python program that stops with a message when a required file is missing.
Output
1 config.ini not found
Approach
sys.exit("message")prints the message to stderr and exits with code 1.
Solution
import subprocessimport sys code = "import os, sys\nif not os.path.exists('config.ini'):\n sys.exit('config.ini not found')"r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)print(r.returncode, r.stderr.strip())Output
1 config.ini not found
Learn the concept
New to this topic? Read the lesson, then come back.