LearnContact
Lesson 5522 min read

Command Line Arguments

Learn how to read command line input with sys.argv and build proper command-line interfaces using the argparse module.

Introduction

Many Python scripts are meant to be run from a terminal, not clicked on in an editor. Command line arguments let you pass information into a script at the moment you run it — like a filename to process or a number of items to generate — without editing the code itself.

Python offers two main ways to handle this: the low-level sys.argv list, and the far more powerful argparse module built for real command-line tools.

What You Will Learn
  • How to access raw command line arguments with sys.argv.
  • Why sys.argv becomes limiting for anything beyond trivial scripts.
  • How to build a proper parser with argparse.
  • The difference between positional and optional arguments.
  • How argparse generates --help text automatically.

What Are Command Line Arguments?

Command line arguments are extra pieces of text typed after a script's name when you run it from a terminal. They let the same script behave differently each time it runs.

Example terminal command
python greet.py Alex --loud

Here, greet.py is the script, "Alex" is a value being passed in, and --loud is an optional flag. The script can read and react to both.

Using sys.argv

The built-in sys module exposes argv, a list containing every word typed on the command line, including the script name itself at index 0.

argv_demo.py
import sys

print("All arguments:", sys.argv)
print("Script name:", sys.argv[0])

if len(sys.argv) > 1:
    print("First argument:", sys.argv[1])
Run it
python argv_demo.py Alex 16
Output
All arguments: ['argv_demo.py', 'Alex', '16']
Script name: argv_demo.py
First argument: Alex

Every value in sys.argv is always a string, even things that look like numbers — "16" would need int("16") before being used in math.

Limits of sys.argv

sys.argv works fine for a single, simple value, but quickly becomes painful once a script needs multiple options, default values, type checking, or helpful error messages.

No Type Conversion

Every value is a plain string — you must convert types manually.

No Automatic Help

There is no built-in way to show users what arguments are expected.

Manual Validation

You must write your own checks for missing or invalid arguments.

No Named Options

There is no built-in support for flags like --verbose or --output.

When to Move Beyond sys.argv

For anything beyond one or two simple positional values, prefer argparse. It handles conversion, validation, defaults, and help text automatically, saving significant boilerplate code.

The argparse Module

argparse is a built-in module purpose-built for creating command-line interfaces. You describe the arguments your script expects, and argparse handles parsing, validation, type conversion, and help messages for you.

basic_argparse.py
import argparse

parser = argparse.ArgumentParser(description="Greet a user by name.")
parser.add_argument("name", help="The name of the person to greet")

args = parser.parse_args()
print(f"Hello, {args.name}!")
Run it
python basic_argparse.py Alex
Output
Hello, Alex!

Positional & Optional Arguments

argparse supports two kinds of arguments: positional arguments, which are required and identified by their order, and optional arguments, usually written with a leading -- and identified by name.

positional_and_optional.py
import argparse

parser = argparse.ArgumentParser(description="Greet a user.")
parser.add_argument("name", help="The name of the person to greet")
parser.add_argument("--loud", action="store_true", help="Print the greeting in uppercase")

args = parser.parse_args()

greeting = f"Hello, {args.name}!"
if args.loud:
    greeting = greeting.upper()

print(greeting)
Run it
python positional_and_optional.py Alex --loud
Output
HELLO, ALEX!

Positional

Required, identified by position — e.g. name.

Optional

Identified by name, usually starts with -- — e.g. --loud.

store_true

A flag that becomes True if present, False otherwise, with no value needed.

Default Values

Optional arguments can specify a default value using the default parameter, so the script still works sensibly even if the user does not provide that argument.

defaults.py
import argparse

parser = argparse.ArgumentParser(description="Repeat a message.")
parser.add_argument("message", help="The message to print")
parser.add_argument("--times", type=int, default=1, help="How many times to print it")

args = parser.parse_args()

for _ in range(args.times):
    print(args.message)
Run without --times
python defaults.py "Hi there"
Output
Hi there
Run with --times 3
python defaults.py "Hi there" --times 3
Output
Hi there
Hi there
Hi there

The type=int parameter also tells argparse to automatically convert the argument to an integer, and to show an error if the user provides something that is not a valid number.

Automatic Help Text

One of argparse's biggest advantages is that it generates a complete --help message for free, based on the arguments and help text you defined.

Run with --help
python defaults.py --help
Output
usage: defaults.py [-h] [--times TIMES] message

Repeat a message.

positional arguments:
  message        The message to print

options:
  -h, --help     show this help message and exit
  --times TIMES  How many times to print it
Help Comes for Free

You never have to write --help handling yourself. argparse builds it automatically from your parser description and each argument's help text.

Worked Example: A Small CLI Script

Here is a complete small script that takes a required file-like name and an optional count, combining everything covered in this lesson.

greet_cli.py
import argparse

parser = argparse.ArgumentParser(description="Greet someone a number of times.")
parser.add_argument("name", help="Name of the person to greet")
parser.add_argument("--times", type=int, default=1, help="Number of times to repeat the greeting")
parser.add_argument("--loud", action="store_true", help="Shout the greeting in uppercase")

args = parser.parse_args()

for _ in range(args.times):
    greeting = f"Hello, {args.name}!"
    if args.loud:
        greeting = greeting.upper()
    print(greeting)
Run it
python greet_cli.py Maya --times 2 --loud
Output
HELLO, MAYA!
HELLO, MAYA!

Common Mistakes

Avoid These Mistakes
  • Forgetting that sys.argv[0] is the script name, not the first real argument.
  • Not converting sys.argv string values to int/float before doing math.
  • Forgetting type=int (or similar) in add_argument(), leaving values as strings unexpectedly.
  • Using action="store_true" but still trying to pass a value to that flag.
  • Writing custom help text and error handling that argparse would have generated automatically.

Best Practices

  • Use argparse instead of sys.argv for anything beyond a single trivial value.
  • Always add a helpful description and per-argument help text.
  • Use type= to let argparse validate and convert values automatically.
  • Provide sensible default= values for optional arguments where possible.
  • Test your script with --help to confirm the generated usage message makes sense.

Frequently Asked Questions

When should I use sys.argv instead of argparse?

Only for extremely small, throwaway scripts with a single simple argument. For anything a real user might run, argparse's validation and help text are worth the small extra setup.

Are argparse values always converted to the right type?

Only if you specify type= in add_argument(). Without it, all values are captured as plain strings, same as sys.argv.

What happens if a required positional argument is missing?

argparse automatically prints a usage error message and exits the script, without you writing any extra code.

Can an argument have both a short and long name, like -t and --times?

Yes, pass both to add_argument(), for example add_argument("-t", "--times", ...), and either form will work on the command line.

Is argparse part of the Python standard library?

Yes, it ships with Python and requires no installation, similar to the sys, json, and csv modules covered earlier.

Key Takeaways

  • sys.argv gives raw access to command line arguments as a list of strings.
  • sys.argv lacks type conversion, validation, and automatic help text.
  • argparse is the standard tool for building real command-line interfaces.
  • Arguments can be positional (required) or optional (named with --).
  • argparse generates --help output automatically from your argument definitions.

Summary

Command line arguments let a single script behave differently based on what the user types when running it. sys.argv provides raw access, but argparse turns that raw access into a polished, validated, self-documenting interface.

In this lesson, you learned how to read arguments with sys.argv, why argparse is preferred for real scripts, how to define positional and optional arguments with defaults, and how argparse generates help text automatically.

Lesson 55 Completed
  • You can read raw command line arguments with sys.argv.
  • You can build a parser with argparse, including positional and optional arguments.
  • You understand default values and automatic --help generation.
  • You are ready to learn about type hints.
Next Lesson →

Type Hints