Size of objects

Size of objects

Easysys Module Programs · 12 of 20

Write a Python program that compares the memory size of a few objects.

Output
True
True

Approach

  1. sys.getsizeof.

Solution

Python
import sys small, big = [], list(range(1000))print(sys.getsizeof(small) < sys.getsizeof(big))print(sys.getsizeof("") < sys.getsizeof("python"))
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

Import from a custom folder

Import from a custom folder

Mediumsys Module Programs · 10 of 20

Write a Python program that adds a folder to sys.path and imports a module from it.

Output
Hello, SQA Tools!

Approach

  1. Append the folder, then import.

Solution

Python
import osimport sys os.makedirs("my_libs", exist_ok=True)with open(os.path.join("my_libs", "greetings.py"), "w") as f:    f.write("def hello(name):\n    return f'Hello, {name}!'\n") sys.path.append(os.path.abspath("my_libs"))import greetings print(greetings.hello("SQA Tools"))
Output
Hello, SQA Tools!
Tip

For real projects, install your package (pip install -e .) instead of changing sys.path.

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Which modules are loaded?

Which modules are loaded?

Easysys Module Programs · 11 of 20

Write a Python program that checks whether a module has been imported yet.

Output
False
True

Approach

  1. sys.modules holds every loaded module.

Solution

Python
import sys print("json" in sys.modules)import jsonprint("json" in sys.modules)
Output
False
True

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Inspect sys.path

Inspect sys.path

Easysys Module Programs · 9 of 20

Write a Python program that shows how many folders Python searches for modules.

Output
list True
True

Approach

  1. sys.path is a list of folder names.

Solution

Python
import sys print(type(sys.path).__name__, len(sys.path) > 0)print(any("site-packages" in p for p in sys.path))
Output
list True
True
Note

The real folder names include your user name on most computers, so the program prints checks instead of the list.

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Write with sys.stdout

Write with sys.stdout

Easysys Module Programs · 8 of 20

Write a Python program that prints a progress bar with sys.stdout.write.

Output
#.... 20%
##... 40%
###.. 60%
####. 80%
##### 100%

Approach

  1. write does not add a newline.

Solution

Python
import sys for step in range(1, 6):    sys.stdout.write("#" * step + "." * (5 - step) + f" {step * 20}%\n")
Output
#.... 20%
##... 40%
###.. 60%
####. 80%
##### 100%

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Read numbers from stdin

Read numbers from stdin

Easysys Module Programs · 7 of 20

Write a Python program that reads numbers from standard input and prints their total.

Input
5, 10, 15 on separate lines
Output
3 numbers, total 30

Approach

  1. Loop over sys.stdin.

Solution

Python
import sys numbers = [int(line) for line in sys.stdin if line.strip()]print(len(numbers), "numbers, total", sum(numbers))
Outputtyped input: 5, 10, 15
3 numbers, total 30

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Write errors to stderr

Write errors to stderr

Easysys Module Programs · 6 of 20

Write a Python program that writes normal output to stdout and errors to stderr.

Output
stdout: report ready
stderr: warning: 2 tests skipped

Approach

  1. print(..., file=sys.stderr); run it and capture both streams separately.

Solution

Python
import subprocessimport sys code = "import sys\nprint('report ready')\nprint('warning: 2 tests skipped', file=sys.stderr)"r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True)print("stdout:", r.stdout.strip())print("stderr:", r.stderr.strip())
Output
stdout: report ready
stderr: warning: 2 tests skipped

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Check the Python version

Check the Python version

Easysys Module Programs · 4 of 20

Write a Python program that checks it is running on Python 3.10 or newer.

Output
3
supported

Approach

  1. Compare sys.version_info with a tuple.

Solution

Python
import sys print(sys.version_info.major)print("supported" if sys.version_info >= (3, 10) else "please upgrade")
Output
3
supported

Learn the concept

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

More sys module programs

← All 20 sys Module Programs

Detect the operating system

Detect the operating system

Easysys Module Programs · 5 of 20

Write a Python program that prints a different message per operating system.

Output
Windows

Approach

  1. sys.platform is “win32”, “linux” or “darwin”.

Solution

Python
import sys if sys.platform.startswith("win"):    print("Windows")elif sys.platform == "darwin":    print("macOS")else:    print("Linux or another Unix")
Output
Windows

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 status code

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.

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

Learn the concept

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

More sys module programs

← All 20 sys Module Programs