Exit with a message

Easysys Module Programs · 18 of 20

Write a Python program that stops with a message when a required file is missing.

Advertisement
Output
1 config.ini not found

Approach

  1. sys.exit("message") prints the message to stderr and exits with code 1.

Solution

Python
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.

More sys module programs

← All 20 sys Module Programs

Leave a Comment