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.
Code
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) # 最后一次的退出码交给进程:0Output
Captured from a sandboxed run of this snippet in the build pipeline.
no args -> 2
bad input -> 1
processed good_nameHow 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.