Python CLI Options: argparse, Click, Typer for Beginners

目次

1. Introduction

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.
LibraryFeaturesEase of useRecommended use
argparseStandard Python library and built-in toolMediumSmall to medium-sized scripts
ClickIntuitive and easy to create commandsHighLarge-scale CLI applications
TyperLeverages type hints to make Click more PythonicHighAPI 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.
import argparse

# Create ArgumentParser object
parser = argparse.ArgumentParser(description="Example of Python command-line arguments")

# Add command-line option
parser.add_argument("--name", type=str, required=True, help="Please specify a name")

# Parse arguments
args = parser.parse_args()

# Display result
print(f"Hello, {args.name}!")

Execution example

python script.py --name Alice

Output

Hello, Alice!
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.
import typer

app = typer.Typer()

@app.command()
def greet(name: str):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    app()

Execution example

python script.py greet --name Alice

Output

Hello, Alice!
Thus, by using Typer, you can treat function arguments directly as command-line options, allowing more intuitive code.

Summary

LibraryFeaturesUse caseInstallation required
argparseStandard library, no additional installationSmall scriptsNo
ClickCan write concisely using decoratorsLarge CLI applicationsYes
TyperIntuitive code using type hintsAPI development and data processingYes

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.
import argparse

# Create ArgumentParser object
parser = argparse.ArgumentParser(description="Example of Python command-line arguments")

# Define command-line arguments
parser.add_argument("--name", type=str, required=True, help="Please specify a name")

# Parse arguments
args = parser.parse_args()

# Output results
print(f"Hello, {args.name}!")

Example execution

python script.py --name Alice

Output

Hello, Alice!
In this script, the --name argument is required, and an error occurs if the argument is not provided.

4.3 Required arguments and optional arguments

In argparse, you can define two types of arguments: required arguments (positional arguments) and optional arguments.

Required arguments (positional arguments)

Positional arguments are passed without specifying a particular option name.
parser.add_argument("name", type=str, help="Please specify a name")
Example
python script.py Alice
Output
Hello, Alice!

Optional arguments

Optional arguments are passed with a leading -- or - and are optional.
parser.add_argument("--age", type=int, help="Please specify an age")
Example
python script.py --age 25
Output
Age: 25

4.4 Setting default values

You can also set a default value for an argument when it is not provided.
parser.add_argument("--city", type=str, default="Tokyo", help="Please specify a city")
Example (no arguments)
python script.py
Output
City: Tokyo

4.5 Receiving multiple arguments

By specifying nargs="+", you can receive multiple values as a list.
parser.add_argument("--fruits", nargs="+", help="Please specify your favorite fruits")
Example
python script.py --fruits apple banana orange
Output
Favorite fruits: ['apple', 'banana', 'orange']

4.6 Flag (True/False) options

You can define flag options using store_true or store_false.
parser.add_argument("--verbose", action="store_true", help="Show detailed information")
Example
python script.py --verbose
Output
Displaying detailed information

4.7 Automatic generation of help messages

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

Summary

FeatureMethod
Required arguments (positional arguments)parser.add_argument("name", type=str)
Optional argumentsparser.add_argument("--age", type=int)
Setting default valuesparser.add_argument("--city", default="Tokyo")
Receiving multiple argumentsparser.add_argument("--fruits", nargs="+")
Flag optionsparser.add_argument("--verbose", action="store_true")
Automatic help generationpython script.py --help

5. 【Python】How to Use Click

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.

Defining positional arguments (required arguments)

@click.command()
@click.argument("name")
def greet(name):
    click.echo(f"Hello, {name}!")

if __name__ == "__main__":
    greet()
Example execution
python script.py Alice
Output
Hello, Alice!

Defining 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.

CLI with subcommands

@click.group()
def cli():
    pass

@cli.command()
def hello():
    click.echo("Hello!")

@cli.command()
def bye():
    click.echo("Goodbye!")

if __name__ == "__main__":
    cli()
Example execution
python script.py hello
Output
Hello!
By using Click’s @click.group(), you can build CLI apps with multiple commands.

Conclusion

Click featureSyntax
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.

Basic Typer Script

import typer

app = typer.Typer()

@app.command()
def greet(name: str = "Guest"):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    app()

Execution Example

python script.py greet --name Alice

Output

Hello, Alice!

Key Points

  • app = typer.Typer(): Create the application’s entry point
  • @app.command(): Register the function as a CLI command
  • name: str = "Guest": Set a default value using type hints
  • print(): Since Typer internally uses click.echo(), using print() is also safe

6.4 Required Arguments and Optional Arguments

In Typer, by leveraging type hints, you can easily define required (positional) arguments and optional arguments.

Defining Required (Positional) Arguments

@app.command()
def greet(name: str):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    app()
Execution Example
python script.py greet Alice
Output
Hello, Alice!

Defining Optional Arguments

@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.

CLI with Subcommands

@app.command()
def hello():
    print("Hello!")

@app.command()
def bye():
    print("Goodbye!")

if __name__ == "__main__":
    app()
Execution Example
python script.py hello
Output
Hello!
In Typer, you can easily implement multiple commands by simply defining @app.command() multiple times.

Summary

Typer FeatureHow to Write
Basic Command@app.command()
Optional Argumenttyper.Option(...)
Required Argumentname: str
Flag Optiontyper.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

ItemargparseClickTyper
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 casesSmall scriptsMedium to large‑scale CLI toolsType‑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
  • Example: simple log‑analysis script, batch processing tool
✅ If you want to create CLI tools intuitively, Click
  • Leverages decorators for intuitive syntax
  • Subcommands and flag options can be added easily
  • Prompt feature (click.prompt()) is built‑in
  • Example: terminal‑based applications, data‑processing scripts
✅ 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

ConditionBest library
Want to stay within the standard libraryargparse
Want to create a CLI with short codeClick
Want to leverage type hints to improve code readabilityTyper
Want to create a simple scriptargparse
Want intuitive user input without a GUIClick or Typer
Want to develop a large‑scale CLI applicationClick or Typer

7.4 Real‑world selection examples for argparse, Click, and Typer

Use caseSuitable librarySpecific applications
Add simple arguments to a scriptargparseFile‑processing scripts, batch jobs
Create a simple CLI appClickFile‑management tools, data‑conversion tools
Develop a type‑safe CLITyperData analysis, machine‑learning tools
Develop a tool with multiple subcommandsClick or TyperGit‑like CLI applications
Need a prompt (input form)ClickTools that request user input
Want to build a CLI while leveraging type hintsTyperCommand‑line tool for APIs

7.5 Conclusion: Which one should you choose?

Your goalRecommended library
Want to stay within Python’s standard featuresargparse
Want to create an intuitive CLI with short codeClick
Want to use type hints and write highly readable codeTyper
Need user input (prompt)Click
Want to build a CLI app with many subcommandsClick 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
  • Click leverages decorators for easy writing and is suited for large‑scale CLI tools
  • Typer leverages 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.
import argparse

parser = argparse.ArgumentParser(description="Sample script")
parser.add_argument("--name", type=str, help="Please specify a name")
args = parser.parse_args()
print(f"Hello, {args.name}!")

8.2 Which should I choose, Click or Typer?

Q: Which should I choose, Click or Typer? A:
  • 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.
LibrarySuitable Use Cases
ClickGeneral CLI tool development. When there are many options or subcommands are used
TyperWhen 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 SizeRecommended Library
Simple script (1–3 options)argparse
Medium-sized script (5 or more options)Click
Want to create type-safe scriptsTyper

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.

Example: Creating a CLI tool like git

import argparse

parser = argparse.ArgumentParser(description="Subcommand example")
subparsers = parser.add_subparsers(dest="command")

# hello command
hello_parser = subparsers.add_parser("hello", help="Say hello")
hello_parser.add_argument("name", type=str, help="Please specify a name")

# run
args = parser.parse_args()
if args.command == "hello":
    print(f"Hello, {args.name}!")
Example
python script.py hello Alice
Output
Hello, Alice!
If you use many subcommands, Click is more intuitive to write, so choose based on the situation.

8.5 What are the benefits of using Typer?

Q: What is the biggest advantage of using Typer? A: The biggest advantage of Typer is that you can leverage type hints.
  • argparse and Click require you to explicitly specify option types, but Typer can use Python’s type hints directly, making the code simpler.
  • IDE autocomplete is enhanced, improving development efficiency.
Example: Using type hints with Typer
import typer

app = typer.Typer()

@app.command()
def greet(name: str):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    app()
In this code, simply specifying the type hint name: str automatically enables type checking for the CLI option.

Summary

  • argparse is a standard library and is suitable for simple CLI scripts.
  • Click is easy to write by leveraging decorators and is suited for large-scale CLI tools.
  • Typer leverages type hints, enabling highly readable CLI development.
Choose the appropriate library and develop more efficient CLI tools!
年収訴求