Q1What does sys.path represent?
sys and argparse — Runtime Info and Argument Parsing
Learn the Python sys and argparse modules from the ground up. From reading runtime info with sys.path / sys.argv / sys.exit to building structured argument parsers with argparse — all hands-on.
This article walks through the sys module, which gives you access to the Python runtime, and the argparse module, which structures command-line arguments. You'll cover the basics of sys.path / sys.argv / sys.exit, then move on to defining arguments with type conversion, defaults, and choices using argparse's ArgumentParser.
The sys Module — Reading the Python Runtime
The sys module is a standard library that gives you access to information about the running Python process itself. What can be imported (sys.path), what was passed in from the command line (sys.argv), the Python version and platform (sys.version / sys.platform), and how to terminate the process (sys.exit) — information and functions about Python itself all live here.
| Attribute / Function | Type | Meaning |
|---|---|---|
| sys.path | list[str] | List of folders where import looks for modules |
| sys.argv | list[str] | List of command-line arguments passed in |
| sys.version | str | Python version string |
| sys.platform | str | OS identifier ('darwin' / 'linux' / 'win32', etc.) |
| sys.exit(code) | function | Terminate the process with the given exit code |
| sys.stdout | TextIO | Standard output. Where print writes to |
`sys.path` is the list of folders that import searches for modules, scanned in order from the top. With for p in sys.path: you can print each registered folder one line at a time. In the Pyodide runtime you'll see paths like /lib/python312.zip / /lib/python3.12 / /lib/python3.12/lib-dynload / /lib/python3.12/site-packages, while a regular Python install lists the standard library folder and site-packages (where pip-installed libraries go).
sys.platform is an attribute that returns the OS identifier as a string. In the browser's Pyodide runtime it shows emscripten (on a real machine you'll see darwin (Mac) / win32 (Windows) / linux). It's used when you need to branch on the operating system.
import sys
print("Platform:", sys.platform)
# Mac: Platform: darwin
# Windows: Platform: win32
# Linux: Platform: linux
# Browser: Platform: emscripten
sys.argv and argparse — Handling Command-Line Arguments
On a real Python install, when you run a command like python script.py user_name 42, the tokens land in sys.argv as a list of strings. sys.argv[0] is the script name, and sys.argv[1:] holds the arguments you passed in. The argparse module is a standard library that reads sys.argv and converts it into an object you can access by attribute, letting you declare type conversion, default values, and choice restrictions in a clean way.
sys.argv. The first entry is the script name, so the actual arguments start at sys.argv[1:].# script.py (intended to run on a real Python install)
import sys
print(sys.argv)
# Example: running python script.py user_name 42 produces
# ['script.py', 'user_name', '42']
# The actual arguments start at [1:]
args = sys.argv[1:]
print(args) # ['user_name', '42']
sys.argv is essentially empty in the browser
The browser runtime this series uses doesn't have a command line at all, so sys.argv only holds a fixed value like ['<exec>']. Check the real-machine behavior in the code block above; in the hands-on practice you'll substitute by passing a list directly in place of sys.argv.
Once you start manually pulling apart `sys.argv`, you immediately hit requirements like converting strings to numbers, supporting optional flags, or printing a usage message with --help. Python ships argparse as a standard library to handle all of this for you, and the basic flow is three steps — create an ArgumentParser, register the arguments you want to receive with add_argument, then convert them to values with parse_args.
# Real-machine Python style
import argparse
parser = argparse.ArgumentParser(description="Product search CLI")
parser.add_argument("--keyword", required=True) # pass as --keyword Apple
parser.add_argument("--limit", type=int, default=10) # auto-converted to int
args = parser.parse_args() # reads sys.argv[1:]
print(args.keyword, args.limit)
--keyword Apple --limit 5 into an object you can access by attribute as args.keyword / args.limit.In the browser, use parse_args(list) form
Since the browser runtime has no sys.argv, calling parse_args() with no arguments throws an error. Use the same list-passing form you'd use in tests — parse_args(["--keyword", "Apple", "--limit", "5"]). On a real machine, omitting that list automatically uses sys.argv[1:].
argparse In Depth — Type Conversion, Defaults, Choices
add_argument has several options that control how an argument behaves. Four of them cover almost every practical CLI use case.
| Option | Effect | Example |
|---|---|---|
| type | Convert the received string to another type | type=int → '5' becomes 5 |
| default | Default value when the argument is omitted | default=10 |
| required | Make it required; error if missing | required=True |
| choices | Restrict to a list of allowed values | choices=['asc', 'desc'] |
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--keyword", required=True)
parser.add_argument("--limit", type=int, default=10)
parser.add_argument("--order", choices=["asc", "desc"], default="asc")
args = parser.parse_args(["--keyword", "Apple", "--limit", "5", "--order", "desc"])
print(args.keyword, args.limit, args.order)
# -> Apple 5 desc
Combining type and default
When you specify both type=int, default=10, the argument gets 10 (int) when omitted, and the passed value gets converted to int when supplied. default values are not run through type conversion, so write the default already in the target type. Writing default="10" would put the string "10" in only when the argument is omitted — a subtle bug.
sys.exit — Returning an Exit Code
sys.exit(code) is a function that takes a number and terminates the process. By convention, 0 means success and any non-zero value (usually 1) means failure, and CI systems and shell scripts branch on this value to decide what to do next. Internally, it raises a SystemExit exception. You can catch it with try / except, but you usually let it propagate so the process exits.
import sys
price = -100
if price < 0:
print("Error: price is negative")
sys.exit(1) # nothing after this point runs
print("Continuing...") # only runs when price >= 0
sys.exit(0) signals success and sys.exit(1) signals failure to the caller (a shell or CI). On a real machine you can check the exit code with $? in the shell. If you don't call sys.exit, the script runs through to the last line.Knowledge Check
Answer each question one by one.
Q2Which best describes sys.exit(1)?
Q3When you want to try argparse in the browser, which approach can you use in place of sys.argv?