Passing Variables to Python Scripts
CU Boulder ATOC
Spring 2026
FCQs are open for this coourse
Check your grade
Submit any late assignments by Thursday 23rd 12pm
Final presentation by Monday 27th 1:30-4pm
Office Hours:
Will: Tu 11:15-12:15p Th 9-10a Aerospace Cafe
Aiden: M / W 330-430p DUAN D319

sys.argv (the low-level way)argparseYou wrote a script that analyzes temperature data:
What if you want to test a different threshold? Edit the file. Run. Edit again. Run again…
What if a collaborator wants to use it? They edit the file. Now you have two versions.
sys.argvsys.argv: What the Shell Sends PythonEvery time you run a Python script, the shell sends a list of strings called sys.argv:
You can read these manually:
Why sys.argv Alone Is Fragile
argparseargparse?argparse is a standard library module — it ships with Python, no install needed.
It does three things for you automatically:
| What you need | Without argparse |
With argparse |
|---|---|---|
Convert "35.0" → float |
float(sys.argv[2]) by hand |
type=float |
| Fallback when arg is missing | try/except IndexError |
default=35.0 |
| Tell users how to run the script | Write a README | --help is auto-generated |
| Catch bad input early | Crash deep in your code | Clear error before main() runs |
# This is what argparse gives you for free:
$ python analyze_climate.py --help
usage: analyze_climate.py [-h] [--thresh THRESH] [--n-days N_DAYS]
Analyze temperature extremes.
options:
-h, --help show this help message and exit
--thresh THRESH temperature threshold in °C (default: 35.0)
--n-days N_DAYS number of days to analyze (default: 90)argparse in Four Stepsimport argparse
# 1. Create a parser
parser = argparse.ArgumentParser(description="Analyze temperature extremes.")
# 2. Define your arguments
parser.add_argument("--thresh", type=float, default=35.0, help="temperature threshold (°C)")
parser.add_argument("--n-days", type=int, default=90, help="number of days to analyze")
parser.add_argument("--outfile", type=str, default="output.png", help="output figure path")
# 3. Parse the command line
args = parser.parse_args()
# 4. Use args like object attributes
print(f"Threshold: {args.thresh}")
print(f"Days: {args.n_days}") # note: hyphens become underscores
print(f"Output: {args.outfile}")Now --help works automatically:
$ python analyze_climate.py --help
usage: analyze_climate.py [-h] [--thresh THRESH] [--n-days N_DAYS] [--outfile OUTFILE]
Analyze temperature extremes.
options:
--thresh THRESH temperature threshold (°C) (default: 35.0)
--n-days N_DAYS number of days to analyze (default: 90)
--outfile OUTFILE output figure path (default: output.png)# analyze_climate.py
import argparse
import numpy as np
def main():
parser = argparse.ArgumentParser(
description="Count days exceeding a temperature threshold."
)
parser.add_argument("--datafile", type=str, required=True, help="path to .npy temperature file")
parser.add_argument("--thresh", type=float, default=35.0, help="threshold in °C (default: 35)")
parser.add_argument("--n-days", type=int, default=None, help="limit analysis to first N days")
parser.add_argument("--outfile", type=str, default="out.png", help="output figure filename")
args = parser.parse_args()
data = np.load(args.datafile)
if args.n_days is not None:
data = data[:args.n_days]
hot_days = np.sum(data > args.thresh)
print(f"Days above {args.thresh}°C: {hot_days} / {len(data)}")
# ... plotting code here ...
if __name__ == "__main__":
main()add_argument Options| Option | What it does | Example |
|---|---|---|
type= |
Converts string → Python type automatically | type=float |
default= |
Value used when argument is omitted | default=35.0 |
required=True |
Crashes with a clear message if omitted | for mandatory inputs |
help= |
Text shown in --help output |
help="threshold in °C" |
choices= |
Restricts to a list of valid values | choices=["mean","max","min"] |
nargs="+" |
Accepts one or more values as a list | --years 2020 2021 2022 |
Hyphens vs underscores: --n-days on the command line → args.n_days in code. argparse converts automatically.
Positional vs Optional Arguments
--thresh (two dashes) → optional, can be omitted if it has a defaultdatafile (no dashes) → positional, must be provided in orderWhat happens when you run this?
error: argument --thresh: invalid float value: 'warm'
argparse catches the bad type before your code even runs. Compare this to sys.argv, where you’d get a cryptic ValueError deep inside your script.
You want to run an ensemble weather simulation with a configurable number of members and random seed:
Write the add_argument calls (don’t write the full script — just the three lines):
Bonus: what is args.n_members (not args.n-members) and why?
Hyphens in argument names are replaced with underscores in args — Python identifiers can’t contain hyphens.
sys.argv gives raw access to command-line strings, but you handle all conversion and errors yourselfargparse gives you type conversion, defaults, help text, and error messages for freemain() and guard with if __name__ == "__main__" — this makes it both runnable and importablerequired=True for inputs that genuinely have no sensible default (like an input data file)--helpOffice Hours:
Will: Tu 11:15-12:15p / Th 9-10a Aerospace Café
Aiden: M / W 3:30-4:30p DUAN D319
Useful docs:

ATOC 4815/5815 - Passing Variables to Scripts