On this page
sys
Prev: symtable | Up: stdlib_module | Next: sysconfig
Rel: sysconfig, builtins, warnings, dataclasses, contextlib
Ref: docs.python.org — sys
Tags: #public #python3 #stdlib
Import
import sys
Overview
Direct interface to the Python interpreter's runtime state: command-line arguments (sys.argv), standard I/O streams (stdin/stdout/stderr), module search path (sys.path), exit codes (sys.exit), and active exception/recursion controls. Use argparse for real CLI flag parsing rather than slicing sys.argv manually.
Quick Start
import sys
print(f"Python {sys.version_info.major}.{sys.version_info.minor} on {sys.platform}")
print("diagnostic message", file=sys.stderr)
assert sys.version_info >= (3, 10)
Implementation Walkthrough
1. Clean CLI Entry Point with Separate stdout / stderr & Exit Codes
Keep machine-readable results on sys.stdout and human diagnostics on sys.stderr, returning an integer exit code to sys.exit():
import sys
def main(argv: list[str] | None = None) -> int:
args = sys.argv[1:] if argv is None else argv
if not args:
print("error: expected at least one argument", file=sys.stderr)
return 2
print(" ".join(args), file=sys.stdout)
return 0
if __name__ == "__main__":
raise SystemExit(main())
2. Reading Piped stdin Only When Not Interactive
import sys
if not sys.stdin.isatty():
piped_text = sys.stdin.read()
Gotchas & Boundaries
sys.exit()raisesSystemExit: It is aBaseException(notException), sofinallyblocks run, butexcept BaseException:will accidentally swallow it.- Don't mutate
sys.pathin production packages: Rely on proper packaging (pyproject.toml, virtualenvs) instead ofsys.path.insert(0, ...). sys.getsizeof()is shallow: It measures only the container object itself, not the objects referenced inside alistordict.- Raising
sys.setrecursionlimit()too high can segfault CPython: Refactor deep recursion into an explicit stack loop instead.
Common Functions
- sys.activate_stack_trampoline() —
activate_stack_trampoline(backend, /)— Activate stack profiler trampoline backend. - sys.addaudithook() —
addaudithook(hook)— Adds a new audit hook callback. - sys.audit() —
audit(event, /, *args)— Passes the event to any audit hooks that are attached. - sys.breakpointhook() —
breakpointhook(*args, **kwargs)— This hook function is called by built-in breakpoint(). - sys.call_tracing() —
call_tracing(func, args, /)— Call func(*args), while tracing is enabled. - sys.deactivate_stack_trampoline() —
deactivate_stack_trampoline()— Deactivate the current stack profiler trampoline backend. - sys.displayhook() —
displayhook(object, /)— Print an object to sys.stdout and also save it in builtins._ - sys.exc_info() —
exc_info()— Return current exception information: (type, value, traceback). - sys.excepthook() —
excepthook(exctype, value, traceback, /)— Handle an exception by displaying it with a traceback on sys.stderr. - sys.exception() —
exception()— Return the current exception. - sys.exit() —
exit(status=None, /)— Exit the interpreter by raising SystemExit(status). - sys.get_asyncgen_hooks() —
get_asyncgen_hooks()— Return the installed asynchronous generators hooks. - sys.get_coroutine_origin_tracking_depth() —
get_coroutine_origin_tracking_depth()— Check status of origin tracking for coroutine objects in this thread. - sys.get_int_max_str_digits() —
get_int_max_str_digits()— Return the maximum string digits limit for non-binary int<->str conversions. - sys.getallocatedblocks() —
getallocatedblocks()— Return the number of memory blocks currently allocated. - sys.getdefaultencoding() —
getdefaultencoding()— Return the current default encoding used by the Unicode implementation. - sys.getdlopenflags() —
getdlopenflags()— Return the current value of the flags that are used for dlopen calls. - sys.getfilesystemencodeerrors() —
getfilesystemencodeerrors()— Return the error mode used Unicode to OS filename conversion. - sys.getfilesystemencoding() —
getfilesystemencoding()— Return the encoding used to convert Unicode filenames to OS filenames. - sys.getprofile() —
getprofile()— Return the profiling function set with sys.setprofile. - sys.getrecursionlimit() —
getrecursionlimit()— Return the current value of the recursion limit. - sys.getrefcount() —
getrefcount(object, /)— Return the reference count of object. - sys.getsizeof() —
getsizeof(object [, default]) -> int— Return the size of object in bytes. - sys.getswitchinterval() —
getswitchinterval()— Return the current thread switch interval; see sys.setswitchinterval(). - sys.gettrace() —
gettrace()— Return the global debug tracing function set with sys.settrace. - sys.getunicodeinternedsize() —
getunicodeinternedsize(*, _only_immortal=False)— Return the number of elements of the unicode interned dictionary - sys.intern() —
intern(string, /)— ``Intern'' the given string. - sys.is_finalizing() —
is_finalizing()— Return True if Python is exiting. - sys.is_remote_debug_enabled() —
is_remote_debug_enabled()— Return True if remote debugging is enabled, False otherwise. - sys.is_stack_trampoline_active() —
is_stack_trampoline_active()— Return True if a stack profiler trampoline is active. - sys.remote_exec() —
remote_exec(pid, script)— Executes a file containing Python code in a given remote Python process. - sys.set_asyncgen_hooks() —
set_asyncgen_hooks([firstiter] [, finalizer])— Set a finalizer for async generators objects. - sys.set_coroutine_origin_tracking_depth() —
set_coroutine_origin_tracking_depth(depth)— Enable or disable origin tracking for coroutine objects in this thread. - sys.set_int_max_str_digits() —
set_int_max_str_digits(maxdigits)— Set the maximum string digits limit for non-binary int<->str conversions. - sys.setdlopenflags() —
setdlopenflags(flags, /)— Set the flags used by the interpreter for dlopen calls.
Constants & Attributes
sys.abiflags(str) =''sys.api_version(int) =1013sys.argv(list) =['/Users/curtis/.gemini/tasks/c_eca7e9bd5d5a5631/workspac...sys.base_exec_prefix(str) ='/opt/homebrew/opt/python@3.14/Frameworks/Python.framewor...sys.base_prefix(str) ='/opt/homebrew/opt/python@3.14/Frameworks/Python.framewor...sys.builtin_module_names(tuple) =('_abc', '_ast', '_codecs', '_collections', '_contextvars...sys.byteorder(str) ='little'sys.copyright(str) ='Copyright (c) 2001 Python Software Foundation.\nAll Righ...sys.dont_write_bytecode(bool) =Falsesys.exec_prefix(str) ='/opt/homebrew/opt/python@3.14/Frameworks/Python.framewor...sys.executable(str) ='/opt/homebrew/opt/python@3.14/bin/python3.14'sys.flags(flags) =sys.flags(debug=0, inspect=0, interactive=0, optimize=0, ...sys.float_info(float_info) =sys.float_info(max=1.7976931348623157e+308, max_exp=1024,...sys.float_repr_style(str) ='short'sys.hash_info(hash_info) =sys.hash_info(width=64, modulus=2305843009213693951, inf=...
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/abc
- tuts/python3/stdlib_module/antigravity
- tuts/python3/stdlib_module/ast
- tuts/python3/stdlib_module/atexit
- tuts/python3/stdlib_module/builtins
- tuts/python3/stdlib_module/code
- tuts/python3/stdlib_module/codeop
- tuts/python3/stdlib_module/compileall
- tuts/python3/stdlib_module/contextlib
- tuts/python3/stdlib_module/dataclasses
- tuts/python3/stdlib_module/dis
- tuts/python3/stdlib_module/ensurepip
- tuts/python3/stdlib_module/gc
- tuts/python3/stdlib_module/importlib
- tuts/python3/stdlib_module/inspect
- tuts/python3/stdlib_module/keyword
- tuts/python3/stdlib_module/modulefinder
- tuts/python3/stdlib_module/opcode
- tuts/python3/stdlib_module/pickletools
- tuts/python3/stdlib_module/pkgutil
- tuts/python3/stdlib_module/py_compile
- tuts/python3/stdlib_module/pyclbr
- tuts/python3/stdlib_module/pyexpat
- tuts/python3/stdlib_module/runpy
- tuts/python3/stdlib_module/site
- tuts/python3/stdlib_module/sre_compile
- tuts/python3/stdlib_module/sre_constants
- tuts/python3/stdlib_module/sre_parse
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/symtable
- tuts/python3/stdlib_module/sys/activate_stack_trampoline
- tuts/python3/stdlib_module/sys/addaudithook
- tuts/python3/stdlib_module/sys/audit
- tuts/python3/stdlib_module/sys/breakpointhook
- tuts/python3/stdlib_module/sys/call_tracing
- tuts/python3/stdlib_module/sys/deactivate_stack_trampoline
- tuts/python3/stdlib_module/sys/displayhook
- tuts/python3/stdlib_module/sys/exc_info
- tuts/python3/stdlib_module/sys/excepthook
- tuts/python3/stdlib_module/sys/exception
- tuts/python3/stdlib_module/sys/exit
- tuts/python3/stdlib_module/sys/get_asyncgen_hooks
- tuts/python3/stdlib_module/sys/get_coroutine_origin_tracking_depth
- tuts/python3/stdlib_module/sys/get_int_max_str_digits
- tuts/python3/stdlib_module/sys/getallocatedblocks
- tuts/python3/stdlib_module/sys/getdefaultencoding
- tuts/python3/stdlib_module/sys/getdlopenflags
- tuts/python3/stdlib_module/sys/getfilesystemencodeerrors
- tuts/python3/stdlib_module/sys/getfilesystemencoding
- tuts/python3/stdlib_module/sys/getprofile
- tuts/python3/stdlib_module/sys/getrecursionlimit
- tuts/python3/stdlib_module/sys/getrefcount
- tuts/python3/stdlib_module/sys/getsizeof
- tuts/python3/stdlib_module/sys/getswitchinterval
- tuts/python3/stdlib_module/sys/gettrace
- tuts/python3/stdlib_module/sys/getunicodeinternedsize
- tuts/python3/stdlib_module/sys/intern
- tuts/python3/stdlib_module/sys/is_finalizing
- tuts/python3/stdlib_module/sys/is_remote_debug_enabled
- tuts/python3/stdlib_module/sys/is_stack_trampoline_active
- tuts/python3/stdlib_module/sys/remote_exec
- tuts/python3/stdlib_module/sys/set_asyncgen_hooks
- tuts/python3/stdlib_module/sys/set_coroutine_origin_tracking_depth
- tuts/python3/stdlib_module/sys/set_int_max_str_digits
- tuts/python3/stdlib_module/sys/setdlopenflags
- tuts/python3/stdlib_module/sysconfig
- tuts/python3/stdlib_module/tabnanny
- tuts/python3/stdlib_module/this
- tuts/python3/stdlib_module/token
- tuts/python3/stdlib_module/tokenize
- tuts/python3/stdlib_module/traceback
- tuts/python3/stdlib_module/venv
- tuts/python3/stdlib_module/warnings
- tuts/python3/stdlib_module/zipapp
- tuts/python3/stdlib_module/zipimport
- tuts/python3/tutorials/advanced_python_internals/memory_management_and_internals
- tuts/python3/tutorials/core_fundamentals/syntax_and_variables
- tuts/python3/tutorials/intermediate_python_and_software_engineering/modules_packages_and_tooling
Related notes
- tuts/python3/stdlib_module/builtins Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/contextlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/symtable Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sys/activate_stack_trampoline Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sys/addaudithook Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sys/audit Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sys/breakpointhook Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sys/call_tracing Linked here; links to this page; shared tags: #stdlib