Python sys 模块

argv, path, exit codes, stdin/stdout, and interpreter limits.

Intermediate
Key Points`sys.argv` is the raw CLI contract; `sys.exit(1)` sets the process status that CI and supervisors read.

Command Line Arguments

sys.argv[0] is the script name; the rest are strings. Beyond two arguments, switch to argparse.

Python
# demo.py
import sys

print(sys.argv)
Bash
python3 demo.py --mode prod 8080
Output
['demo.py', '--mode', 'prod', '8080']

Exit Codes and Streams

sys.exit(0) means success. Logs go to stderr, data to stdout — mixing them breaks downstream pipes.

Python
import sys

def main() -> int:
    if len(sys.argv) < 2:
        print("usage: demo.py <file>", file=sys.stderr)
        return 2
    print(f"processing {sys.argv[1]}")
    return 0

sys.exit(main())
Output
usage: demo.py <file>

Path and Interpreter

Python
import sys

print(sys.version.split()[0])      # 3.12.3
print(sys.executable)              # 解释器绝对路径
print(sys.platform)                # 'win32' / 'linux'

sys.path.insert(0, "/opt/myapp")   # 临时加入搜索路径(别写进生产代码)
print(sys.getrecursionlimit())     # 默认 1000
Output
3.12.3
/usr/bin/python3
linux
1000
Raising the recursion limit turns RecursionError into a segfault. Rewrite recursion as iteration or an explicit stack.

Friends & Partners