- __init__() function
- Aliases
- and operator
- argparse
- Arrays
- Booleans
- Bytes
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Context manager
- Data class
- Data structures
- datetime module
- Decorator
- Dictionaries
- Docstrings
- enum
- enumerate() function
- Equality operator
- Exception handling
- False
- File handling
- Filter()
- Flask framework
- Floats
- Floor division
- For loops
- Formatted strings
- Functions
- Generator
- Globals()
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Iterator
- Lambda function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List count()
- List insert() method
- List pop() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Merge sort
- Min()
- Modules
- Multiprocessing
- Multithreading
- None
- not operator
- NumPy library
- OOP
- or operator
- Pandas library
- Parameters
- pathlib module
- Pickle
- print() function
- Property()
- Random module
- range() function
- Raw strings
- Recursion
- Reduce()
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- SQLite
- String decode()
- String find()
- String join() method
- String replace() method
- String split() method
- String strip()
- Strings
- Ternary operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- Virtual environment
- While loops
- Zip function
PYTHON
Python argparse: Syntax, Usage, and Examples
Python argparse is a built-in module that helps you create user-friendly command-line interfaces. It allows you to define the arguments your program expects, parse them from the command line, and access them in a structured way. This makes argparse Python's standard solution for command-line argument parsing.
You can use argparse in Python to handle required arguments, optional flags, default values, type checking, and more. It enables your script to behave more like a real command-line tool, improving usability and automation.
Why Use argparse in Python?
Using argparse simplifies the process of building command-line tools by replacing manual parsing of sys.argv
. With just a few lines, you can:
- Define what arguments your program requires
- Automatically generate help messages
- Validate argument types
- Support flags and optional inputs
If you want your Python scripts to be accessible and flexible for users, argparse offers an organized and readable way to collect input.
Getting Started with argparse Python
To begin using argparse, you first need to import the module and create a parser object:
import argparse
parser = argparse.ArgumentParser()
This parser becomes the central object that you use to define and retrieve command-line arguments.
Adding Arguments with add_argument()
The add_argument()
method tells argparse which command-line options your program accepts:
parser.add_argument("filename")
args = parser.parse_args()
print(args.filename)
When you run the script like this:
python script.py data.txt
It prints:
data.txt
This simple interface allows you to build more complex parsing logic with ease.
Positional vs Optional Arguments
In Python argparse, positional arguments are required by default. Optional arguments are created by adding a --
prefix:
parser.add_argument("input_file")
parser.add_argument("--verbose", action="store_true")
The --verbose
flag is optional and behaves like a boolean switch. You can activate it with:
python script.py file.txt --verbose
This automatically sets args.verbose
to True
.
argparse Python Example: Basic Script
Here's a complete example using positional and optional arguments:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("input")
parser.add_argument("--output", default="out.txt")
parser.add_argument("--verbose", action="store_true")
args = parser.parse_args()
print("Input:", args.input)
print("Output:", args.output)
print("Verbose:", args.verbose)
You can run it like this:
python example.py file.txt --verbose --output result.txt
This showcases how you can handle multiple inputs in a simple script.
Argument Types and Type Conversion
By default, argparse treats all arguments as strings. Use the type
keyword to specify the data type:
parser.add_argument("--count", type=int)
If a user enters an invalid type, argparse shows a helpful error message automatically.
You can also handle float values, files, or even custom validation functions.
Python argparse Default Value
Use the default
parameter to specify fallback values if the user omits the argument:
parser.add_argument("--timeout", type=int, default=30)
If --timeout
isn't supplied, args.timeout
will default to 30. This makes it easy to configure sane defaults without requiring the user to input everything manually.
The concept of a Python argparse default value is common in configuration-heavy applications like deployment scripts or test automation tools.
Python argparse Required Argument
Optional arguments can be made required by setting required=True
:
parser.add_argument("--config", required=True)
The script now throws an error if --config
isn’t specified. This lets you enforce user input while still using --
style options.
Handling Boolean Flags
You can add boolean arguments using store_true
or store_false
:
parser.add_argument("--debug", action="store_true")
This sets args.debug
to True
only if the user provides the flag. Otherwise, it remains False
.
Boolean flags are ideal for toggles like verbose mode, dry runs, or logging options. This is where the concept of a python argparse flag becomes useful.
Collecting Lists with nargs
Use the nargs
parameter to collect multiple values into a list:
parser.add_argument("--files", nargs="+")
Run it like this:
python script.py --files one.txt two.txt three.txt
The args.files
variable now holds ["one.txt", "two.txt", "three.txt"]
.
You can also use nargs="*"
to accept zero or more values, or nargs=2
to require an exact number.
Learning to use python argparse nargs is helpful when building interfaces that accept variable input sizes.
Limiting Input with Choices
You can limit argument values using the choices
keyword:
parser.add_argument("--mode", choices=["train", "test", "eval"])
The parser now restricts input to valid options, and provides clear error messages if a user enters something unexpected.
Constants with const
Use the const
keyword when you want to associate a specific value with a flag:
parser.add_argument('--reset', action='store_const', const=0)
This sets args.reset
to 0 when --reset
is provided. You can also pair this with nargs
to create toggle-style arguments.
A python argparse add_argument const scenario often arises when mapping specific flags to predefined configurations.
Handling Lists with Custom Types
You can combine nargs
with custom types to parse and validate user input:
def csv_to_list(value):
return value.split(",")
parser.add_argument("--ids", type=csv_to_list)
Run it like this:
python script.py --ids=1,2,3
Now args.ids
is ['1', '2', '3']
. This approach lets you handle python argparse list inputs without post-processing.
argparse with Subcommands
You can build CLI tools with subcommands using add_subparsers()
:
subparsers = parser.add_subparsers(dest="command")
train_parser = subparsers.add_parser("train")
train_parser.add_argument("--epochs", type=int)
eval_parser = subparsers.add_parser("eval")
eval_parser.add_argument("--metrics", nargs="*")
Users can now call:
python script.py train --epochs 10
python script.py eval --metrics accuracy loss
This pattern is common in tools like Git and Docker, and allows more modular command-line programs.
argparse and Environment Variables
Although argparse doesn't support environment variables natively, you can combine it with os.environ
:
import os
parser.add_argument("--api-key", default=os.getenv("API_KEY"))
This enables fallback from the environment if no command-line argument is given.
argparse for Boolean Values with Strings
If users pass boolean flags like --enable=True
, convert the string manually:
def str_to_bool(value):
return value.lower() in ("yes", "true", "t", "1")
parser.add_argument("--enable", type=str_to_bool)
Now --enable=True
or --enable=yes
is treated as True
.
This solves issues that arise from user input not matching the expected Python boolean format. It’s a popular workaround in the context of python argparse boolean arguments.
argparse in Scripts and Production Tools
Argparse is widely used in production environments for scripts that:
- Train machine learning models
- Deploy infrastructure with scripts
- Run scheduled jobs
- Control data pipelines
Its flexibility and simplicity make it a go-to choice when building reusable automation scripts.
Example: Full argparse Python Script
import argparse
parser = argparse.ArgumentParser(description="File processor")
parser.add_argument("filepath", help="Path to the input file")
parser.add_argument("--mode", choices=["read", "write"], required=True)
parser.add_argument("--repeat", type=int, default=1)
parser.add_argument("--tags", nargs="*", default=[])
args = parser.parse_args()
print("Processing:", args.filepath)
print("Mode:", args.mode)
print("Repeat:", args.repeat)
print("Tags:", args.tags)
You can now run this script with a variety of arguments, using lists, optional values, and validated inputs.
The Python argparse module gives you a powerful, built-in solution for building command-line interfaces. With just a few lines, you can define positional and optional arguments, handle boolean flags, enforce types, supply default values, and even accept lists.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.