On this page
  1. sys
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Clean CLI Entry Point with Separate stdout / stderr & Exit Codes
  7. 2. Reading Piped stdin Only When Not Interactive
  8. Gotchas & Boundaries
  9. Common Functions
  10. Constants & Attributes

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

Common Functions

Constants & Attributes

Linked from

Related notes