Python is a flexible and powerful programming language used by many developers. By leveraging command-line options, you can improve the usability of scripts and applications. In this article, we will thoroughly explain how to handle command-line options in Python. Specifically, we will introduce three options: the standard library argparse, the external library Click, and Typer, and discuss their differences and when to use each.
2. What are Python command-line options?
When you use command-line options in Python, you can pass arguments at script execution time to control its behavior. For example, consider the following script.
python script.py --name Alice --age 25
By using option arguments like this, users can customize the script’s behavior.
2.1 Why is option parsing necessary?
When creating Python scripts, you can receive input from standard input, but leveraging command-line options allows you to provide a flexible and intuitive user interface. The benefits include:
Improved script versatility (can run with different parameters)
Interact with users without building a GUI (suitable for terminal operations)
Ability to change behavior without a configuration file
Python offers several libraries for parsing command-line options. Among them, the three most important are:
2.2 Comparison of argparse, Click, and Typer
There are several ways to parse command-line options in Python, and the representative ones are summarized in the table below.
Library
Features
Ease of use
Recommended use
argparse
Standard Python library and built-in tool
Medium
Small to medium-sized scripts
Click
Intuitive and easy to create commands
High
Large-scale CLI applications
Typer
Leverages type hints to make Click more Pythonic
High
API design and data processing
3. How to handle command-line options in Python
There are several ways to parse command-line options in Python, with the representative libraries being argparse (standard library), Click (external library), and Typer (type‑hint support). Here we explain the features and basic usage of each library.
3.1 argparse: Implementation using the standard library
argparse is a library that comes standard with Python, usable without any additional installation. It can parse basic arguments and automatically generate help messages.
argparse Main Features
Because it’s a Python standard library, no additional installation is required
Easily set required and optional arguments
Automatically generates help messages
Example
The following code is a simple script that uses argparse to accept the --name option argument and print it.
Thus, by using Python’s standard argparse, you can easily handle option arguments.
3.2 Click: A more concise way to write
Click is a library that leverages decorators to allow intuitive writing of command-line options. It enables implementing the same functionality with more concise code than argparse.
<>Installing Click
Since Click is an external library, it needs to be installed beforehand.
pip install click
Example
The following is an example of handling the --name option using Click.
import click
@click.command()
@click.option("--name", prompt="What is your name?", help="Please specify a name")
def greet(name):
click.echo(f"Hello, {name}!")
if __name__ == "__main__":
greet()
Execution example
python script.py
Output
What is your name? Alice
Hello, Alice!
Thus, using Click, you can also prompt the user for input.
3.3 Typer: Intuitive writing using type hints
Typer is a library built on top of Click, featuring the ability to write more intuitively by leveraging Python type hints.
Installing Typer
Since Typer is also an external library, it needs to be installed beforehand.
pip install typer
Example
The following is an example of handling the --name option using Typer.
Thus, by using Typer, you can treat function arguments directly as command-line options, allowing more intuitive code.
Summary
Library
Features
Use case
Installation required
argparse
Standard library, no additional installation
Small scripts
No
Click
Can write concisely using decorators
Large CLI applications
Yes
Typer
Intuitive code using type hints
API development and data processing
Yes
4. [Python] How to Use argparse
Python’s standard library argparse is a powerful tool for parsing command-line options. This section provides a detailed explanation of argparse from basic usage to advanced applications.
4.1 What is argparse?
argparse is a library that comes standard with Python and makes it easy to parse arguments when running scripts. It is more concise and readable than handling sys.argv directly, and includes features such as automatic help message generation.
Features of argparse
Standard library, so no additional installation required
Easy to set up optional and required arguments
Automatically generates help messages
Can easily define arguments of different data types
4.2 Basic usage
First, let’s look at the basic usage of argparse.
Simple argument parsing example
The following code creates a script that receives the command-line argument --name and displays its value.
In argparse, specifying -h or --help automatically generates a help message. Example
python script.py --help
Output
usage: script.py [-h] --name NAME
Example of Python command-line arguments
optional arguments:
-h, --help show this help message and exit
--name NAME Please specify a name
Python’s external library Click is a powerful tool that lets you create command-line interfaces (CLI) more simply and intuitively than argparse. This section provides a detailed explanation from basic usage of Click to advanced examples.
5.1 What is Click?
Click (Command Line Interface Creation Kit) is a library for easily creating CLI tools in Python. Compared to argparse, it features an intuitive decorator-based syntax and is suitable for managing multiple subcommands.
Features of Click
Decorator-based simple syntax
Nested subcommands can be created easily
Built-in prompt functionality (asks for input)
Automatic generation of help messages
Using Click, you can implement CLI with more intuitive and concise code.
5.2 Installing Click
Since Click is not part of the standard library, you need to install it first.
pip install click
5.3 Basic Usage of Click
Let’s create a simple CLI app using Click. The following code is a script that receives the --name option and displays a greeting.
Basic Click script
import click
@click.command()
@click.option("--name", prompt="What is your name?", help="Please specify a name")
def greet(name):
click.echo(f"Hello, {name}!")
if __name__ == "__main__":
greet()
Example execution
python script.py
Output
What is your name? Alice
Hello, Alice!
Key points
@click.command(): defines the function as a CLI command
@click.option("--name", prompt="What is your name?"): defines an option argument and prompts for input when none is given
click.echo(): safely handles standard output
In this way, using Click lets you create CLI more intuitively than argparse.
5.4 Required arguments and optional arguments
In Click, you can easily define both positional arguments (required arguments) and option arguments.
@click.command()
@click.option("--age", type=int, help="Please specify the age")
def show_age(age):
click.echo(f"Your age is {age} years.")
if __name__ == "__main__":
show_age()
Example execution
python script.py --age 25
Output
Your age is 25 years.
5.5 Flag (True/False) options
In Click, setting is_flag=True lets you create flag options that handle boolean values.
Defining flag options
@click.command()
@click.option("--verbose", is_flag=True, help="Show detailed information")
def run(verbose):
if verbose:
click.echo("Running in verbose mode...")
else:
click.echo("Running in normal mode.")
if __name__ == "__main__":
run()
Example execution
python script.py --verbose
Output
Running in verbose mode...
5.6 CLI app with multiple options
Using Click, you can easily create CLI apps that have multiple options.
Example combining multiple options
@click.command()
@click.option("--name", default="Guest", help="Please specify a name")
@click.option("--count", default=1, type=int, help="Please specify the number of greetings")
def greet(name, count):
for _ in range(count):
click.echo(f"Hello, {name}!")
if __name__ == "__main__":
greet()
Example execution
python script.py --name Alice --count 3
Output
Hello, Alice!
Hello, Alice!
Hello, Alice!
5.7 Implementing subcommands
In Click, you can also create CLI tools with multiple commands.
By using Click’s @click.group(), you can build CLI apps with multiple commands.
Conclusion
Click feature
Syntax
Basic command
@click.command()
Option argument
@click.option("--name")
Required argument
@click.argument("name")
Flag option
@click.option("--verbose", is_flag=True)
Subcommand
@click.group() usage
Using Click makes developing CLI tools in Python more intuitive than argparse. In particular, the ease of prompt functionality and subcommands are major strengths of Click.
6. [Python] How to Use Typer
Python’s external library Typer is a library for building CLI tools based on Click, characterized by being able to write more intuitively by leveraging type hints. This section provides a detailed explanation from the basic usage of Typer to its handy features.
6.1 What is Typer?
Typer is a library that leverages Python’s type hints to create more concise and readable CLIs. Because it inherits Click’s powerful features while allowing type-safe code, more Pythonic CLI development becomes possible.
Features of Typer
Define arguments intuitively by leveraging type hints
Based on Click, enabling the construction of powerful CLI tools
IDE autocomplete becomes easier to use
Implement default values and validation easily with type hints
A library provided by the developers of FastAPI
6.2 Installing Typer
Typer is an external library, so it needs to be installed beforehand.
pip install typer
6.3 Basic Usage of Typer
With Typer, you can easily create CLI tools while leveraging type hints. The following code is a script that receives the --name option and displays a greeting.
@app.command()
def show_age(age: int = typer.Option(..., help="Please specify the age")):
print(f"Your age is {age} years.")
if __name__ == "__main__":
app()
Execution Example
python script.py show-age --age 25
Output
Your age is 25 years.
For optional arguments, you can use typer.Option(...) and add help="description" to automatically generate a help message.
6.5 Flag (True/False) Options
In Typer, setting is_flag=True allows you to create flag options that handle boolean values.
Defining Flag Options
@app.command()
def run(verbose: bool = typer.Option(False, "--verbose", help="Show detailed information")):
if verbose:
print("Running in verbose mode...")
else:
print("Running in normal mode.")
if __name__ == "__main__":
app()
Execution Example
python script.py run --verbose
Output
Running in verbose mode...
6.6 CLI App with Multiple Options
With Typer, you can easily create CLI apps that have multiple options.
Example Combining Multiple Options
@app.command()
def greet(name: str = "Guest", count: int = 1):
for _ in range(count):
print(f"Hello, {name}!")
if __name__ == "__main__":
app()
Execution Example
python script.py greet --name Alice --count 3
Output
Hello, Alice!
Hello, Alice!
Hello, Alice!
6.7 Implementing Subcommands
Typer also allows you to create CLI tools with multiple commands.
In Typer, you can easily implement multiple commands by simply defining @app.command() multiple times.
Summary
Typer Feature
How to Write
Basic Command
@app.command()
Optional Argument
typer.Option(...)
Required Argument
name: str
Flag Option
typer.Option(False, "--verbose", is_flag=True)
Subcommand
@app.command() defined multiple times
Using Typer makes developing CLI tools in Python more intuitive than with argparse or Click. In particular, the ability to write code that leverages type hints is a major advantage of Typer.
7. Which library should you choose?
Python as a method for parsing command-line options, we introduced three: argparse, Click, Typer.
Each library has its own characteristics, and the suitable choice varies depending on the project.
In this section, we will revisit each library’s features and explain which one you should choose.
7.1 Comparison table of argparse, Click, and Typer
Item
argparse
Click
Typer
Standard library
✅ (no additional installation required)
❌ (requires installation)
❌ (requires installation)
Conciseness of syntax
❌ (somewhat verbose)
✅ (uses decorators)
✅ (leverages type hints)
Ease of handling optional arguments
◯ (flexible but a bit complex)
✅ (can be defined intuitively)
✅ (can be defined with type hints)
Automatic generation of help messages
✅ (standard support)
✅ (standard support)
✅ (standard support)
Ease of handling subcommands
❌ (somewhat complex)
✅ (can be defined easily)
✅ (can be defined intuitively)
Prompt feature (user input)
❌ (not supported by default)
✅ (standard support)
✅ (standard support)
Support for type hints
❌ (none)
❌ (none)
✅ (available)
Suitable use cases
Small scripts
Medium to large‑scale CLI tools
Type‑safe CLI tools
7.2 Recommended libraries by use case
✅ For small scripts, argparse
Python standard library, so no additional installation required
Can quickly create simple CLI tools
Allows fine‑grained control of options and arguments
✅ If you want type‑safe, highly readable code, Typer
Uses type hints to enhance IDE autocomplete
Based on Click, enabling powerful CLIs to be built easily
Code is highly readable, and function definitions become the CLI specification
Example: data‑analysis tools, CLI for machine‑learning models, CLI for API development
7.3 Selection criteria for each library
Condition
Best library
Want to stay within the standard library
argparse
Want to create a CLI with short code
Click
Want to leverage type hints to improve code readability
Typer
Want to create a simple script
argparse
Want intuitive user input without a GUI
Click or Typer
Want to develop a large‑scale CLI application
Click or Typer
7.4 Real‑world selection examples for argparse, Click, and Typer
Use case
Suitable library
Specific applications
Add simple arguments to a script
argparse
File‑processing scripts, batch jobs
Create a simple CLI app
Click
File‑management tools, data‑conversion tools
Develop a type‑safe CLI
Typer
Data analysis, machine‑learning tools
Develop a tool with multiple subcommands
Click or Typer
Git‑like CLI applications
Need a prompt (input form)
Click
Tools that request user input
Want to build a CLI while leveraging type hints
Typer
Command‑line tool for APIs
7.5 Conclusion: Which one should you choose?
Your goal
Recommended library
Want to stay within Python’s standard features
argparse
Want to create an intuitive CLI with short code
Click
Want to use type hints and write highly readable code
Typer
Need user input (prompt)
Click
Want to build a CLI app with many subcommands
Click or Typer
Each library has its own pros and cons, and making the right choice based on the use case is important.
Summary
argparse is a Python standard library and is suitable for small scripts
Clickleverages decorators for easy writing and is suited for large‑scale CLI tools
Typerleverages type hints to create intuitive and type‑safe CLIs
Choosing the appropriate library based on project size and required features is essential
8. FAQ (Frequently Asked Questions)
We have compiled frequently asked questions about Python command-line option libraries (argparse, Click, Typer). This supplements the previous material and provides detailed explanations of points that can be confusing in actual use.
8.1 What is the difference between argparse and optparse?
Q: What is the difference between argparse and optparse? Which should I use? A:
optparse was a library used in the Python 2 era and has been deprecated since Python 3.2.
argparse is the successor to optparse and enables more flexible option parsing.
Using argparse is now recommended.
Example: With argparse, you can easily customize default values, subcommands, and help messages.
Click is ideal for general-purpose CLI tool development and allows you to easily create CLI apps by leveraging Click‘s own decorator syntax.
Typer builds on Click and its strength is the ability to use type hints. It’s suitable when you want type-safe code or want to take advantage of IDE autocomplete features.
Library
Suitable Use Cases
Click
General CLI tool development. When there are many options or subcommands are used
Typer
When you want to leverage type hints and write highly readable code
8.3 Should I use Click or Typer even for small scripts?
Q: Should I use Click or Typer even for small scripts? Is argparse insufficient? A:
For simple scripts, argparse is sufficient. Since it’s a standard library, you can implement it easily without any additional installation.
However, if options increase and the script becomes more complex, it’s a good idea to consider Click or Typer.
Guidelines for Choosing
Script Size
Recommended Library
Simple script (1–3 options)
argparse
Medium-sized script (5 or more options)
Click
Want to create type-safe scripts
Typer
8.4 How to create subcommands with argparse?
Q: How can I create subcommands with argparse like git? A: With argparse, you can create subcommands using subparsers.