Lesson 28 of 30

In progress

Course progress

Python

Command-line arguments with argparse

Read arguments, add typed flags and defaults, and turn a script into a tool other people can run without editing it.

A script that hard-codes the filename is a script you edit every time you use it. Arguments let the same program work on different inputs, and argparse gives you help text and error messages for free.

What you will learn

  • Read raw arguments from sys.argv.
  • Define typed options, defaults and flags with argparse.
  • Structure a script with main(argv) and meaningful exit codes.

The raw list

sys.argv is a list of strings. The first item is the script name; the rest are whatever the user typed after it.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

In a real script the list comes from sys.argv, but passing it into a function keeps the parsing testable. That small design choice is why the example runs here without a terminal.

Indexing sys.argv[1] without checking the length raises IndexError with a message about list indices, which tells the user nothing. argparse exists to replace that with a usage message.

argparse in four lines

import argparse
parser = argparse.ArgumentParser(description="Count words in a file.")
parser.add_argument("path", help="file to read")
parser.add_argument("--top", type=int, default=10, help="how many results")
args = parser.parse_args()
print(args.path, args.top)

add_argument with a plain name creates a required positional argument. A name starting with -- creates an optional flag, and type=int converts it. Without type=int, args.top is the string "10", and comparing it with a number fails later.

argparse also generates -h/--help, rejects unknown flags, and exits with status 2 and a usage message when a required argument is missing. You get a usable interface without writing validation for each option.

Flags, choices and defaults

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("path")
parser.add_argument("--format", choices=["text", "json"], default="text")
parser.add_argument("--verbose", action="store_true")
parser.add_argument("--limit", type=int, default=0)
args = parser.parse_args()

Positional arguments are required by default. nargs="?" makes one optional, and nargs="*" accepts any number, which is useful for a list of files. Subcommands such as add, list and done use add_subparsers; that is worth learning once a script grows past three modes, and it keeps each mode’s flags separate.

action="store_true" turns --verbose into a boolean that is false unless present. choices rejects anything else with a clear message. default makes the common case short.

Boolean flags are a common source of confusion: --verbose True is not how store_true works, because the flag itself is the value. If you need an explicit on/off value, use type=lambda value: value.lower() == "true" or a pair of flags.

Structure the script

import argparse
import sys
def build_parser():
parser = argparse.ArgumentParser(description="Count words.")
parser.add_argument("path")
parser.add_argument("--top", type=int, default=10)
return parser
def run(path, top):
print(f"reading {path}, showing {top}")
return 0
def main(argv=None):
args = build_parser().parse_args(argv)
return run(args.path, args.top)
if __name__ == "__main__":
sys.exit(main())

main(argv=None) lets tests pass a list and production use the real command line. Returning an integer and passing it to sys.exit makes the exit status explicit: zero for success, non-zero for failure. Shell scripts and CI systems read that number.

Arguments or input?

Use arguments for values known before the program starts: a filename, a mode, a threshold. Use input() for a conversation: confirming a destructive action, or a quiz answer. A tool that asks five questions could usually have taken five flags, and a tool that takes twenty flags probably wants a config file.

Print errors to sys.stderr, not stdout, so that piping the output somewhere does not mix error text into the data.

Using parser.parse_args() at import time makes the module unusable from another script, because importing it parses whatever arguments that script received. Keep parsing inside main() or a function, and let the __main__ guard call it.

Write summarise(argv) that accepts a filename and an optional --min value using argparse, then returns the number of scores at or above the minimum. Test it by passing a list instead of reading the real command line.

Show solution
Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

dest="minimum" avoids shadowing the built-in min. Passing argv explicitly is what makes both calls possible in one run; a script calling main() would use the real arguments instead.

Recap

  • sys.argv[0] is the script name; the rest are strings that need converting.
  • argparse gives typed options, defaults, choices, help text and error handling.
  • Parse inside main(argv), return an exit code, and keep the __main__ guard.

Next, you will organise code across files, so a project does not become one enormous script.

Why does my script not see the arguments I passed?
Check the order: the script name comes first, then the arguments. Also confirm you are running the file you edited, not an installed copy with the same name.
Should I use click or typer instead?
Those libraries are pleasant, but they are third-party dependencies. `argparse` ships with Python and covers most scripts. Reach for a library when you need subcommands and richer help, not before.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.