sys.exit Sets Process Exit Codes

Return codes travel through sys.exit: usage errors conventionally return 2, validation failures 1, and the value handed to sys.exit becomes the process status.

PythonCli Tooling

Code

pythonsnippet
25 lines
import sys


def parse_args(argv: list[str]) -> int:
    if len(argv) < 2:
        # convention: process exit code 2 = usage error, 1 = failure, 0 = success
        print("usage: prog <input>", file=sys.stderr)
        return 2
    return 0


def work(name: str) -> int:
    if not name.isidentifier():
        print(f"invalid identifier: {name}", file=sys.stderr)
        return 1
    print(f"processed {name}")
    return 0


code = parse_args([])
print("no args   ->", code)
code = work("12bad")
print("bad input ->", code)
code = work("good_name")
sys.exit(code)  # 最后一次的退出码交给进程:0

Output

Captured from a sandboxed run of this snippet in the build pipeline.

no args   -> 2
bad input -> 1
processed good_name

How it works

sys.exit Sets Process Exit Codes comes down to the functions parse_args and work.

Putting it to use

Signature: def parse_args(argv: list[str]) -> int

The demo output is labeled (processed, bad input ->), so every printed line maps back to its originating operation.

parse_args is what another module would consume; nothing else here is load-bearing for callers.

Core lines

def parse_args(argv: list[str]) -> int:
    if len(argv) < 2:
        # convention: process exit code 2 = usage error, 1 = failure, 0 = success
        print("usage: prog <input>", file=sys.stderr)
        return 2
    return 0
def work(name: str) -> int:
    if not name.isidentifier():
        print(f"invalid identifier: {name}", file=sys.stderr)
        return 1
    print(f"processed {name}")
    return 0

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Every import resolves inside the standard library — `sys`. The file defines `parse_args`, `work` at load time.