Learn by reading through in order

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.

Four Areas the sys Module Covers
sys moduleRuntime infosys.pathsys.versionI/Osys.argvsys.stdoutTerminationsys.exitPython infosys.platform
sys handles runtime info (path / version / platform), I/O (argv / stdout), and process termination (exit) all in one place. Libraries like argparse also rely on sys.argv internally.
Attribute / FunctionTypeMeaning
sys.pathlist[str]List of folders where import looks for modules
sys.argvlist[str]List of command-line arguments passed in
sys.versionstrPython version string
sys.platformstrOS identifier ('darwin' / 'linux' / 'win32', etc.)
sys.exit(code)functionTerminate the process with the given exit code
sys.stdoutTextIOStandard 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).

Pull out the platform and the contents of the module search path from the sys module and display them. The sys module gives you access to information about the running Python process.

① Import the sys module

② Use sys.platform to print the runtime in the form Platform: ◯◯

③ Loop through sys.path with for and print each entry on its own line (replace empty strings '' with a clearer label)

(If your code runs correctly, the explanation will appear.)

Python Editor

Run code to see output

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.

How Command-Line Arguments Land in sys.argv
python script.pyuser_name 42argv[0]'script.py'argv[1]'user_name'argv[2]'42'
Each token on the command line is passed left-to-right as a list into 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)
How argparse Processes Arguments
sys.argv['--keyword', 'Apple','--limit', '5']ArgumentParser+ add_argumentparse_args()args object.keyword / .limitparse
ArgumentParser parses a command-line string like --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:].

Build the argument parser for a product search CLI with argparse. Create a parser that accepts two options, --keyword and --limit, then parse a simulated argument list.

On a real Python install, calling parse_args() with no arguments reads from sys.argv automatically, but since this exercise runs in the browser you'll pass a list to parse_args() manually as a stand-in for sys.argv.

① Import argparse and create a parser

② Register the two arguments --keyword and --limit

③ Parse the list ["--keyword", "Apple", "--limit", "5"] (since the browser has no real sys.argv, pass the list directly)

④ Pull keyword and limit out of the parsed result and print them on a single line, separated by a space

Python Editor

Run code to see output

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.

OptionEffectExample
typeConvert the received string to another typetype=int → '5' becomes 5
defaultDefault value when the argument is omitteddefault=10
requiredMake it required; error if missingrequired=True
choicesRestrict to a list of allowed valueschoices=['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.

Define the arguments for an inventory search CLI, complete with type conversion, default values, and choices. Confirm that omitting --limit falls back to the default.

On a real machine, parse_args() with no arguments reads from sys.argv automatically, but since you're running in the browser you'll pass a simulated argument list directly.

① Import argparse and create a parser

② Register these three arguments

- --keyword: required

- --limit: integer type, defaults to 10

- --order: either asc or desc, defaults to asc

③ Parse a list equivalent to --keyword Banana --order desc (omitting --limit)

④ Print all three values, keyword, limit, and order, on a single line separated by spaces

Python Editor

Run code to see output

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
Process Termination Flow with sys.exit
sys.exit(0)SuccessExit code 0sys.exit(1)FailureExit code 1No sys.exit callRuns to last lineExit code 0Shell uses $?to check exit code
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.

Write inventory validation with sys.exit. When a negative stock count comes in, the program should fail and the code after it should not run.

① Import sys

② Set the stock count to -3 (to simulate a bad value)

③ If the stock is negative, print Error: stock is negative, then terminate the process with exit code 1

④ Outside the if, print the stock in the form Stock check OK: ◯◯ (this should not run when the stock is negative)

Python Editor

Run code to see output
QUIZ

Knowledge Check

Answer each question one by one.

Q1What does sys.path represent?

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?