Python sys Module Programs with Solutions

Python Practice › sys Module Programs

Python sys Module Programs with Solutions

20 programs18 easy2 medium0 hard

20 sys module programs: command-line arguments, exit codes, stdin/stdout/stderr, the module search path, version checks, recursion limits and object sizes. Programs that need arguments run a small helper script so you can see real results.

Before you start

Read the sys Module and Modules & pip lesson first if the topic is new to you.

All programs

Current exception info

Current exception info

Easysys Module Programs · 20 of 20

Write a Python program that reads the active exception with sys.exception().

Output
KeyError 'missing'

Approach

  1. Inside except, sys.exception() returns the exception being handled (Python 3.11+).

Solution

Python
import sys try:    {}["missing"]except KeyError:    e = sys.exception()    print(type(e).__name__, e)
Output
KeyError 'missing'

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Validate email addresses

Validate email addresses

EasyRegEx Programs · 1 of 20

Write a Python program to check which strings are valid email addresses.

Output
asha@sqatools.in       True
ravi.k+qa@mail.co.uk   True
bad@                   False
no space@x.com         False

Approach

  1. re.fullmatch with a practical email pattern.

Solution

Python
import re pattern = re.compile(r"[\w.+-]+@[\w-]+(\.[\w-]+)+")for e in ["asha@sqatools.in", "ravi.k+qa@mail.co.uk", "bad@", "no space@x.com"]:    print(e.ljust(22), bool(pattern.fullmatch(e)))
Output
asha@sqatools.in       True
ravi.k+qa@mail.co.uk   True
bad@                   False
no space@x.com         False

Line by line

Line 3

Name part, @, a domain and at least one dot-separated part.

Note

No regex covers every legal email address; for sign-ups, send a confirmation email instead of relying on the pattern alone.

Learn the concept

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

More regex programs

← All 20 RegEx Programs

Arguments with argparse

Arguments with argparse

Mediumsys Module Programs · 19 of 20

Write a Python program that parses named options with argparse.

Output
smoke firefox 2

Approach

  1. Pass a list to parse_args to test without a terminal.

Solution

Python
import argparse parser = argparse.ArgumentParser(description="Run tests")parser.add_argument("suite")parser.add_argument("--browser", default="chromium", choices=["chromium", "firefox", "webkit"])parser.add_argument("--retries", type=int, default=0) args = parser.parse_args(["smoke", "--browser", "firefox", "--retries", "2"])print(args.suite, args.browser, args.retries)
Output
smoke firefox 2

Line by line

Line 8

In a real script call parser.parse_args() with no list to read sys.argv.

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Exit with a message

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.

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

Which Python is running?

Which Python is running?

Easysys Module Programs · 16 of 20

Write a Python program that checks which interpreter file is running.

Output
True
True -> not in a virtual environment

Approach

  1. sys.executable.

Solution

Python
import osimport sys print(os.path.basename(sys.executable).lower().startswith("python"))print(sys.prefix == sys.base_prefix, "-> not in a virtual environment" if sys.prefix == sys.base_prefix else "-> in a virtual environment")
Output
True
True -> not in a virtual environment

Line by line

Line 5

Inside a virtual environment sys.prefix differs from sys.base_prefix.

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Byte order and encoding

Byte order and encoding

Easysys Module Programs · 17 of 20

Write a Python program that prints the machine’s byte order and the default text encoding.

Output
little
utf-8

Approach

  1. sys.byteorder and sys.getdefaultencoding().

Solution

Python
import sys print(sys.byteorder)print(sys.getdefaultencoding())
Output
little
utf-8

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Largest list index

Largest list index

Easysys Module Programs · 14 of 20

Write a Python program that prints sys.maxsize and shows ints can be bigger.

Output
True
True

Approach

  1. sys.maxsize limits sizes, not integer values.

Solution

Python
import sys print(sys.maxsize == 2 ** 63 - 1)print(sys.maxsize + 1 > sys.maxsize)
Output
True
True

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Float limits

Float limits

Easysys Module Programs · 15 of 20

Write a Python program that prints the largest float and float precision.

Output
1.7976931348623157e+308
15 decimal digits of precision

Approach

  1. sys.float_info.

Solution

Python
import sys print(sys.float_info.max)print(sys.float_info.dig, "decimal digits of precision")
Output
1.7976931348623157e+308
15 decimal digits of precision

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Recursion limit

Recursion limit

Easysys Module Programs · 13 of 20

Write a Python program that reads the recursion limit and handles RecursionError.

Output
1000
RecursionError caught

Approach

  1. sys.getrecursionlimit().

Solution

Python
import sys print(sys.getrecursionlimit()) def dive(n):    return dive(n + 1) try:    dive(0)except RecursionError:    print("RecursionError caught")
Output
1000
RecursionError caught

Learn the concept

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

More sys module programs

← All 20 sys Module Programs