🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreePython argparse: Parse Command-Line Arguments

Giving a Python program clear command-line inputs starts with defining what callers can supply. argparse lets you define those inputs and read their parsed values in your program.
I’ll show how to define command-line inputs with argparse and explain its Python 3.14 feedback options.
TL;DR
Use argparse.ArgumentParser to define command-line inputs, then call parse_args() to turn them into a Namespace your Python program can use.
- Add positional inputs for required values supplied in order.
- Add options such as --unit for named values and --verbose for switches.
- Python 3.14 adds suggest_on_error and color parser controls.
What Is Python argparse?
argparse is a Python standard-library module for defining and reading command-line arguments. It creates usage and help text from those definitions and reports invalid input through parser errors.
A command-line argument is a value supplied after a program name in a terminal command. For example, in python report.py data.csv --limit 20, the filename is positional and --limit is a named option.
After parsing, use the resulting attributes in the same way as values from any Python object. For example, a declared long option named --output-file is available as args.output_file.
An ArgumentParser object is the central definition of a command interface. Its constructor accepts settings for the program name, description, epilog, formatting, and error behavior. The parser uses those declarations both to interpret arguments and to build help text, so the help screen documents the interface the program actually accepts.
The parser can read process arguments by default, or receive an explicit list through parse_args(args=…). Passing a list is useful when another part of a program needs to parse a known set of tokens. It also keeps parser behavior testable without replacing the process-wide command line.
Set prog when the displayed command name should differ from the invocation Python infers. Set description for a short explanation shown before the arguments, and epilog for a note after them. I keep these values brief because the usage and argument descriptions carry the operational details.
ArgumentParser also supports allow_abbrev, which controls whether a unique prefix can stand in for a long option. Leaving abbreviation enabled can make a short command convenient, but a later option with the same prefix can change what that command means. Set allow_abbrev=False when scripts or automation need option spellings to remain explicit.
| Argument form | Example definition | Typical use |
|---|---|---|
| Positional | parser.add_argument(“filename”) | A required input identified by its position |
| Value option | parser.add_argument(“--limit”, type=int) | An optional named setting with a value |
| Boolean switch | parser.add_argument(“--verbose”, action=”store_true”) | Turn a feature on when the option appears |
I use a positional argument for the primary input and named options for settings because the command then reads in the same order the task is described.
How to Parse Command-Line Arguments with argparse
Define an ArgumentParser, add each input with add_argument(), and call parse_args() before using the values. This example accepts one or more measurements, a unit choice, and a repeatable verbosity switch.
Step 1: Define the parser and its arguments
Save this code in argparse_demo.py. The parser declaration defines the accepted inputs.
import argparse
parser = argparse.ArgumentParser(
description="Summarize a batch of measurements.",
suggest_on_error=True,
color=False,
)
parser.add_argument("values", nargs="+", type=float, metavar="VALUE")
parser.add_argument("--unit", choices=("ms", "s"), default="ms")
parser.add_argument("--verbose", "-v", action="count", default=0)
args = parser.parse_args()
scale = 1000 if args.unit == "s" else 1
values = [value * scale for value in args.values]
print(f"count={len(values)} min={min(values):g} max={max(values):g} {args.unit}")
A larger program can use the verbosity count to select how much diagnostic detail to print.
Step 2: Run the script with values and an option
Run the file with two measurements and the --unit option. I ran the same command from the saved source file and captured this output.
python3 argparse_demo.py 12.5 18 --unit ms -v
count=2 min=12.5 max=18 ms

The summary reports two measurements in milliseconds. The example keeps the output focused on the calculation, while the parsed verbosity setting remains available to code that controls diagnostics.
Step 3: Read the parsed values and help
Ask the parser for its generated help with this command:
python3 argparse_demo.py --help
The help text lists the required values, accepted unit choices, and both spellings of the verbosity option. Review the displayed usage after changing an argument declaration.
Short and long option names can point to the same setting, as in parser.add_argument("-u", "--unit"). The long form is clearer in scripts and documentation, while the short form can reduce typing for frequently used options.
What Should You Check When Using argparse?
Parser feedback options depend on the Python version running the script. The interpreter that launches the program determines which parameters are accepted, even when the source file is shared across machines.
subparsers = parser.add_subparsers(dest="command", required=True)
create = subparsers.add_parser("create")
create.add_argument("--output", required=True)
# command: tool.py create --output backup.tar
| Case | Parser behavior | What to do |
|---|---|---|
| No value for a required positional | Reports a missing required argument and exits with an error | Keep it required when the program cannot proceed without it, or define an optional positional with an intentional default |
| Text supplied where type=int is expected | Reports an invalid value | Use a simple converter such as int for straightforward conversion |
| A choice outside choices | Rejects the value and lists accepted choices | Use choices for a fixed set of valid string values |
| An unknown option | parse_args() reports unrecognized arguments | Correct the spelling or use parse_known_args() only when another component owns the remaining inputs |
For a yes-or-no switch, declare an action rather than converting text with type=bool.
Python 3.14 added suggest_on_error and color to ArgumentParser. Python 3.15 enables suggestions by default.
These settings affect error suggestions and help rendering rather than the values stored in args. Set color=False when a tool expects plain help text.
Check generated help after changing either setting:
python3 argparse_demo.py --help
A path can name a missing file, and a number can fall outside the accepted range. Validate these application rules after parsing so the error can include context.
An option default handles omission when the program has a sensible fallback. Mark a named setting required when continuing without an explicit value would make the operation ambiguous.
A float can be syntactically valid while still being negative when a task requires non-negative measurements.
For short scripts that only need raw values, Python’s command-line arguments guide covers sys.argv and other parsing approaches. When your goal is to launch a function from a terminal, see running Python functions from the command line.
Use dest when an option needs a stable internal attribute name that differs from its public spelling. That can keep downstream code readable while preserving a command-line name that fits the interface.
The parser can also allow an optional positional value and assign it a default. That changes the usage syntax and can make a command less obvious, so use it only when omitting the value has a useful, documented meaning.
| Setting | Effect | Decision |
|---|---|---|
| default | Supplies a value when an option is omitted | Choose a value that works for the ordinary case |
| required=True | Makes an optional spelling mandatory | Use when the named option must be supplied |
| nargs=”?” | Allows a positional value to be absent | Pair with an intentional default |
| choices | Restricts an argument to listed values | Use for a small fixed set |
Use metavar to make the expected value visible in usage text, such as INPUT or VALUE. A concise help string can then explain units or valid interpretation without changing parsing behavior.
Use a clear negative spelling such as --no-cache when a store_false option disables the default behavior.
The table compares input shapes with the values argparse produces.
| Input design | Command shape | Use it when |
|---|---|---|
| One positional value | tool.py INPUT | The command cannot run without a primary input |
| Optional value option | tool.py --format json | The caller may choose a non-default setting |
| Repeated values | tool.py VALUE VALUE | The operation accepts a collection of inputs |
Keep related options’ names and defaults understandable together, especially when other scripts call this command.
Report invalid file inputs with the path and the operation the user attempted.
Describe the same choices in help text that the parser accepts.
Automation depends on predictable help and errors.
When standard output carries machine-readable data, send diagnostics to standard error. That keeps the data stream usable by the next process.
Use pathlib.Path when later code needs path operations. The open call remains the final authority, so handle its error even after checking the path.
Keep parsing separate from work that reads files or calculates results. parse_args() turns tokens into typed values and rejects malformed command syntax. File existence and cross-option rules can be checked once the program has the complete Namespace.
A domain-specific converter can raise argparse.ArgumentTypeError when one token has the wrong format. This is useful for a date or a bounded integer whose validity can be decided from that token alone.
add_argument() returns an Action object representing one declaration. You usually do not need to create that object directly, but knowing the relationship helps when reading parser configuration: each action stores details such as its option strings, destination name, type converter, default and behavior when it is encountered.
The first string passed to add_argument() determines whether the input is positional or optional. A name such as input_file is positional. A string beginning with a prefix such as --output is optional, and short and long spellings can be declared together so both update the same destination.
Use action to define what the parser stores when it sees an option. The default store action records a value, while store_true and store_false represent switches. Choose count to increment an integer or append to collect repeated values.
Custom actions are possible by subclassing argparse.Action, but a built-in action or a type converter fits ordinary parsing. Reserve a custom action for behavior that neither a value conversion nor a standard action can express. Conventional declarations keep generated help and parsed values clear to other developers.
When a declared type conversion fails, argparse turns it into a parser error and prints usage information. A converter should describe the input failure, not perform the whole operation. Converting a token to pathlib.Path is parsing, while opening the file belongs in application logic so file-system errors can include the operation’s context.
parse_known_args() returns both the Namespace and the tokens this parser did not consume. Keep the remainder explicit so a downstream parser receives only the arguments it expects.
ArgumentParser builds a usage line from the declarations. A positional name appears in the order callers must provide it, while an option appears with its spelling and value placeholder. That usage line is a compact contract for the command, so inspect it whenever the interface changes.
For a required input file, a positional name such as source communicates the command’s main subject. A named option is a better fit for a setting callers may omit, such as an output format with a documented default. Avoid making a value optional when the program cannot perform a meaningful operation without it.
Use choices for a small fixed vocabulary, such as the unit names in the example. The parser can reject a misspelled choice and show the allowed values. If the set is discovered dynamically or changes with external data, validate it in application code instead.
Type conversion is about syntax, not every business rule. An integer converter can reject alphabetic text, but it cannot decide whether a particular number is permitted for a given operation. Keep those decisions near the code that understands the operation.
When an option accepts a file path, pathlib.Path provides path operations after parsing. A path object does not guarantee the file exists or can be opened. Attempt the operation and handle the resulting OSError, because permissions or concurrent changes can invalidate an earlier check.
Help output is generated from the same declarations that parse input. Add a short help description for options whose names do not reveal their meaning, then run the help command and compare each documented choice with the parser configuration.
How should I choose between nargs values?
nargs controls how many command-line tokens one argument consumes, so the usage line and parsed value match the input shape.
| nargs | Accepted input | Parsed value | When it fits |
|---|---|---|---|
| omitted | One token | A single value | A required file or setting |
| ? | Zero or one token | A value or its default | An optional positional with a documented fallback |
| * | Zero or more tokens | A list, possibly empty | An optional collection |
| + | One or more tokens | A non-empty list | A required collection such as the measurements above |
| An integer | That number of tokens | A list of fixed length | A coordinate or tuple with a known size |
Each occurrence can carry one value with action="append". Use nargs="+" when the caller supplies a group after one option. Put the selected form in help so callers use it consistently.
parser.add_argument("--tag", action="append", default=[])
# command: tool.py --tag red --tag blue
# args.tag == ["red", "blue"]
What changes when an option is repeated?
Actions determine the parsed value when an option appears. A boolean switch, a counter, and a repeated-value list serve different downstream needs.
For verbosity, a count action stores the number of occurrences, so the program can select diagnostic detail. Set a default for the absent case. A mutually exclusive group can reject conflicting modes before application logic runs.
parser.add_argument("--verbose", "-v", action="count", default=0)
# tool.py -vv gives args.verbose == 2
After adding a negative option such as --no-cache, inspect generated help to confirm the effect of supplying it.
How can I separate commands and their inputs?
Subcommands fit a tool with separate operations, such as creating an archive and listing its contents. Each command can expose arguments relevant to that operation.
Call add_subparsers() to create command parsers. A handler stored with set_defaults(func=…) gives each command a clear dispatch target after parsing.
subparsers = parser.add_subparsers(dest="command", required=True)
create = subparsers.add_parser("create")
create.add_argument("--output", required=True)
# command: tool.py create --output backup.tar
The selected parser validates its own inputs, so a missing output path is tied to create rather than the entire tool. Include a command-level help option when users need details for one operation.
In a standalone command, parse_args() catches misspelled options. Reserve parse_known_args() for a command line that intentionally passes remaining tokens to another parser.
parse_args() returns an argparse.Namespace populated from the declarations. A positional destination uses its name, while --output-file normally becomes output_file because attribute names cannot contain a hyphen. Set dest when the internal name should differ.
When parse_args() sees a required positional that is absent, an option value that is missing, or a token that does not match any declaration, the parser prints usage and an error and exits. This behavior is useful for a command-line program because it stops before the operation runs. A library function should not call parse_args() internally, since doing so would read the caller’s process arguments and could terminate its host application.
Use parse_known_args() when a wrapper deliberately receives arguments for more than one component. It returns the parsed Namespace and unrecognized tokens, which should go to their owning component. Prefix matching can consume a token that begins with a first-parser option, so test the wrapper with its downstream options.
For a top-level program with multiple commands, add_subparsers() gives each subcommand its own parser. The parent parser handles shared settings, and the chosen child parser handles command-specific inputs. Set required=True when a command must be selected, and use a function stored with set_defaults() to dispatch only after parsing has succeeded.
Use mutually exclusive groups for incompatible modes, such as a compact or detailed report. The group can reject both together or require one when no default makes sense. Conditions involving several values or external state belong in application validation, not the parser group.
Keep parser construction at the program boundary. A main function can pass ordinary values to reusable calculations, which keeps them independent of process-wide command-line state.
Conclusion: Keep Argument Rules in the Parser
Start with the inputs the program needs, then add optional behavior only when it has a clear default or effect.
For exact behavior on your supported Python versions, consult the argparse library reference and the Python 3.14 release notes.
FAQ
These answers cover common questions about parser setup and version-specific feedback.
How do I add command-line arguments in Python?
Create an argparse.ArgumentParser, declare each input with add_argument(), then call parse_args() to receive the values in a Namespace.
Which Python version added argparse suggestions and color?
Python 3.14 added the suggest_on_error and color parameters to ArgumentParser. Python 3.15 changed the default for suggest_on_error to True, so check the documentation for the interpreter you support.
How can I show help for an argparse script?
ArgumentParser adds a help option by default. Run the script with the help option to print its generated usage and argument descriptions.


