Python sys module
last modified November 29, 2026 Python 3.15
In this article we show how to use the sys module in Python.
The sys module gives access to variables and functions of the
Python interpreter itself: the command line arguments, the standard input and
output streams, the exit status, the module search path, interpreter limits,
and version information. Functions for working with the operating system, such
as environment variables and files, are in the os
module.
Command line arguments
The sys.argv list holds the command line arguments. The first item
is the name of the script; the arguments follow as strings.
import sys
print(sys.argv)
print('script:', sys.argv[0])
print('number of arguments:', len(sys.argv) - 1)
for i, arg in enumerate(sys.argv[1:], start=1):
print(f'{i}: {arg!r}')
The shell splits the command line into arguments; the quotes keep
two words together as one argument. The enumerate
function numbers the arguments from one. For programs with options and help
text, the argparse module is a better choice.
$ python arguments.py one "two words" 3 ['arguments.py', 'one', 'two words', '3'] script: arguments.py number of arguments: 3 1: 'one' 2: 'two words' 3: '3'
Exit status
The sys.exit function ends the program. An integer argument
becomes the exit status: zero means success, other values mean failure. A
string argument is printed to the standard error output and the status is 1.
import sys
if len(sys.argv) < 2:
sys.exit(f'usage: {sys.argv[0]} NUMBER...')
try:
numbers = [float(arg) for arg in sys.argv[1:]]
except ValueError as e:
print(f'error: {e}', file=sys.stderr)
sys.exit(2)
print(sum(numbers))
The program adds the numbers given on the command line. Without arguments, it
exits with a usage message. A value that is not a number is reported to
sys.stderr and the program exits with status 2. In the shell, the
$? variable holds the status of the last command.
$ python add_numbers.py 1 2.5 4 7.5 $ python add_numbers.py usage: add_numbers.py NUMBER... $ echo $? 1 $ python add_numbers.py 1 x error: could not convert string to float: 'x' $ echo $? 2
Standard streams
The sys.stdin, sys.stdout, and
sys.stderr objects are text files connected to the standard input,
output, and error output. Diagnostic messages belong in
stderr, so that they do not mix with the data in
stdout.
import sys
count = 0
total = 0
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
total += int(line)
count += 1
except ValueError:
sys.stderr.write(f'skipping {line!r}\n')
sys.stdout.write(f'{count} numbers, total {total}\n')
Iterating over sys.stdin reads the input line by line until the
end of input. The program skips empty lines and reports lines that are not
integers to stderr. In the second run, the shell sends the error
output to /dev/null, and only the result remains.
$ printf '10\n20\nabc\n\n5\n' | python streams.py skipping 'abc' 3 numbers, total 35 $ printf '10\n20\nabc\n\n5\n' | python streams.py 2>/dev/null 3 numbers, total 35
Capturing standard output
Since print writes to sys.stdout, we can capture its
output by assigning another file-like object to sys.stdout.
import io
import sys
buffer = io.StringIO()
saved = sys.stdout
sys.stdout = buffer
try:
print('first line')
print('second line')
finally:
sys.stdout = saved
text = buffer.getvalue()
print(f'captured {len(text.splitlines())} lines:')
print(text.upper(), end='')
print(sys.stdout is sys.__stdout__)
An io.StringIO object collects the printed text in memory. The
finally block restores the original stream even if an exception
occurs. The sys.__stdout__ attribute always holds the stream the
interpreter started with. The contextlib.redirect_stdout context
manager does the same swap in a with statement.
$ python redirect.py captured 2 lines: FIRST LINE SECOND LINE True
Interpreter information
The sys.version_info tuple gives the Python version. Other
attributes describe the implementation, the platform, and the interpreter
executable.
import sys
print(sys.version_info)
print(sys.version_info[:2])
print(sys.implementation.name)
print(sys.platform)
print(sys.executable)
if sys.version_info >= (3, 14):
print('template strings are available')
print(sys.flags.optimize, sys.flags.dev_mode)
Since version_info is a tuple, it can be sliced and compared with
other tuples; this is the reliable way to check for a feature version. The
sys.executable path shows which interpreter runs the script, here
the one from a virtual environment. The sys.flags attribute holds
the command line options, such as -O and -X dev.
$ python interpreter.py sys.version_info(major=3, minor=15, micro=2, releaselevel='final', serial=0) (3, 15) cpython linux /home/user/.venv/bin/python template strings are available 0 False
The module search path
The import statement looks for modules in the directories listed
in sys.path. The first item is the directory of the script. Our
project has a lib/greetings.py module.
def greet(name):
return f'Hello there, {name}!'
The module defines one function. The lib directory is not on the
search path, so a plain import greetings in the script would fail
with ModuleNotFoundError.
import sys
from pathlib import Path
print(sys.path[0])
lib = Path(__file__).parent / 'lib'
sys.path.insert(1, str(lib))
import greetings
print(greetings.__file__)
print(greetings.greet('Lucia'))
print('greetings' in sys.modules)
print(sys.modules['greetings'] is greetings)
We insert the lib directory into sys.path before the
import. The sys.modules dictionary holds every module that has
been imported; a second import greetings would return the cached
module without reading the file again. In real projects, a
package installed into the environment is
preferred to changing sys.path by hand.
$ python search_path.py /home/user/sys-module /home/user/sys-module/lib/greetings.py Hello there, Lucia! True True
Imported and standard modules
Besides sys.modules, the module has two sets of module names:
sys.builtin_module_names lists the modules compiled into the
interpreter and sys.stdlib_module_names lists the whole standard
library.
import sys
print(len(sys.modules) > 0)
print('json' in sys.modules)
import json
print('json' in sys.modules)
print(sys.modules['json'].dumps([1, 2]))
print(len(sys.stdlib_module_names) > 200)
print('sqlite3' in sys.stdlib_module_names)
print('requests' in sys.stdlib_module_names)
print('math' in sys.builtin_module_names)
The json module appears in sys.modules only after it
is imported. The stdlib_module_names set, available since Python
3.10, tells whether a name belongs to the standard library;
requests is a third-party package.
$ python modules.py True False True [1, 2] True True False True
Recursion limit
Python limits the depth of nested function calls to protect the interpreter
from running out of stack. The getrecursionlimit and
setrecursionlimit functions read and change the limit.
import sys
def depth(n):
if n == 0:
return 0
return 1 + depth(n - 1)
print(sys.getrecursionlimit())
try:
depth(5000)
except RecursionError as e:
print('error:', e)
sys.setrecursionlimit(6000)
print(depth(5000))
With the default limit of 1000, a recursion 5000 levels deep raises
RecursionError. After raising the limit, the same call succeeds.
Raising the limit is a quick fix; for deep data, an iterative algorithm is
usually the better solution.
$ python recursion.py 1000 error: maximum recursion depth exceeded 5000
Sizes and numeric limits
The sys.maxsize value is the largest index a container can have,
sys.float_info describes the float type, and
sys.getsizeof returns the size of an object in bytes.
import sys
print(sys.maxsize, sys.maxsize == 2**63 - 1)
print(sys.float_info.max)
print(sys.float_info.epsilon)
print(sys.byteorder)
for obj in [0, 2**100, 'a', 'abc', [], [1, 2, 3], {}]:
print(f'{obj!r:35} {sys.getsizeof(obj)}')
Python integers have no maximum value; maxsize only limits the
size of lists, strings, and other containers. The getsizeof
function counts only the object itself, not the objects it refers to: a list
of three integers is 88 bytes plus the integers. The numbers are for a 64-bit
CPython build.
$ python sizes.py
9223372036854775807 True
1.7976931348623157e+308
2.220446049250313e-16
little
0 28
1267650600228229401496703205376 40
'a' 42
'abc' 44
[] 56
[1, 2, 3] 88
{} 64
Integer string conversion limit
Converting a huge integer to a string takes quadratic time. To protect against denial-of-service attacks, Python refuses to convert integers with more than 4300 decimal digits by default.
import sys
print(sys.get_int_max_str_digits())
big = 7 ** 10_000
try:
print(len(str(big)))
except ValueError as e:
print('error:', e)
sys.set_int_max_str_digits(10_000)
print(len(str(big)))
print(str(big)[:20])
The number seven to the power of ten thousand has 8451 digits. The first
conversion fails with a ValueError. The
set_int_max_str_digits function raises the limit for the whole
program; zero turns the limit off. The limit can also be set with the
PYTHONINTMAXSTRDIGITS environment variable.
$ python int_digits.py 4300 error: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit 8451 95587288567444097027
Exceptions and the exception hook
The sys.exception function, added in Python 3.11, returns the
exception that is being handled. The sys.excepthook function is
called for exceptions that nobody catches.
import sys
def parse(text):
try:
return int(text)
except ValueError:
exc = sys.exception()
print('handling', type(exc).__name__, exc.args)
return None
print(parse('42'))
print(parse('forty'))
print('outside:', sys.exception())
def report(exc_type, exc, tb):
print(f'fatal: {exc_type.__name__}: {exc}', file=sys.stderr)
sys.excepthook = report
print('before')
1 / 0
print('not reached')
Inside the except block, sys.exception returns the
ValueError; outside a handler, it returns None. Our
report hook replaces the default traceback with a one-line
message. The program still ends at the uncaught exception, with status 1.
$ python exceptions.py
42
handling ValueError ("invalid literal for int() with base 10: 'forty'",)
None
outside: None
before
fatal: ZeroDivisionError: division by zero
Audit hooks
The interpreter raises audit events for sensitive operations, such as opening
files, starting processes, or importing modules. The
sys.addaudithook function registers a callback for these events.
import sys
def watch(event, args):
if event == 'open':
path, mode, _ = args
print(f'audit: open {path} mode={mode}', file=sys.stderr)
sys.addaudithook(watch)
with open('notes.txt', 'w') as f:
f.write('meeting at 10\n')
with open('notes.txt') as f:
print(f.read(), end='')
Our hook reports every open event to stderr. The
arguments of the event are the path, the mode, and the flags. Audit hooks
cannot be removed once added; they are meant for monitoring and logging, not
as a security sandbox.
$ python audit.py audit: open notes.txt mode=w audit: open notes.txt mode=r meeting at 10
Source
sys – System-specific parameters and functions – Python documentation
Audit events table – Python documentation
In this article we have used the sys module to read arguments,
exit with a status, work with the standard streams and the module search path,
and inspect interpreter limits. See also
Python os module,
Python argparse,
Python subprocess, and
Python exceptions.
Author
List all Python tutorials.