Creating High-Performance Command-Line Tools in Python: How to Use the argparse Module

Unlike sys.argv, which simply receives command-line arguments as a list, using Python’s standard library argparse allows you to easily implement advanced features such as “automatic help message generation,” “argument type checking,” and “option argument processing.” Using this module is recommended when creating full-scale command-line tools.

This article explains how to create a calculator tool that accepts two numbers and an operator using argparse.


目次

Basic Flow of argparse

The procedure for using argparse is broadly divided into the following three steps:

  1. Create Parser: Create an ArgumentParser object.
  2. Add Arguments: Define what arguments to accept (name, type, help, etc.) using the add_argument() method.
  3. Parse Arguments: Execute the parse_args() method to parse and obtain the values passed from the command line.

Practical Code Example: Simple Calculator Tool

We will create a tool calc_tool.py that accepts “two numbers (mandatory)” and an “operator (optional)” from the user and calculates the result.

import argparse

def main():
    # 1. Create Parser
    # The string specified in the description argument is displayed as the tool description in the help
    parser = argparse.ArgumentParser(description="Calculate two numbers with the specified operator")

    # 2. Add Arguments
    
    # Positional Arguments (Mandatory): Defined by name only
    # Specifying type=float automatically converts the received string to a number
    parser.add_argument("num1", type=float, help="First number")
    parser.add_argument("num2", type=float, help="Second number")

    # Option Arguments (Optional): Prefixed with -- or -
    # default: Value used if not specified
    # choices: Restrict received values to a specific list (errors otherwise)
    parser.add_argument("--operator", "-o", type=str, default="+",
                        choices=["+", "-", "*", "/"],
                        help="Specify operator (+, -, *, /). Default is addition")

    # 3. Parse Arguments
    # Command line arguments are parsed, and the result is stored in the args object
    args = parser.parse_args()

    # --- Main Processing ---
    # Access values with args.argument_name
    n1 = args.num1
    n2 = args.num2
    op = args.operator
    result = 0

    # Calculation based on operator
    if op == "+":
        result = n1 + n2
    elif op == "-":
        result = n1 - n2
    elif op == "*":
        result = n1 * n2
    elif op == "/":
        if n2 == 0:
            print("Error: Cannot divide by zero")
            return
        result = n1 / n2

    print(f"Result: {n1} {op} {n2} = {result}")

if __name__ == "__main__":
    main()

Main Parameters of add_argument

  • Positional Arguments ("name"): Arguments that must be specified on the command line. They are interpreted in the order they are defined.
  • Option Arguments ("--name", "-n"): Arguments that do not need to be specified. Prefix names with a hyphen.
  • type: Specifies the type of the value to receive. Specifying int or float automatically performs type conversion and input validation.
  • default: The default value used if the option argument is not specified on the command line.
  • choices: Specifies a list of allowed values. If a value not in the list is entered, an error message is automatically displayed and the program exits.
  • help: A string displayed as a description of that argument when the help message (-h) is shown.

Execution Methods and Results

Execute the script in the terminal (command prompt) to check its behavior.

1. Display Help (-h or --help)

argparse automatically generates a help message based on the definitions.

python calc_tool.py -h

Output:

usage: calc_tool.py [-h] [--operator {+,-,*,/}] num1 num2

Calculate two numbers with the specified operator

positional arguments:
  num1                  First number
  num2                  Second number

options:
  -h, --help            show this help message and exit
  --operator {+,-,*,/}, -o {+,-,*,/}
                        Specify operator (+, -, *, /). Default is addition

2. Basic Execution (Mandatory Arguments Only)

Execute by specifying only the positional arguments. Since the option argument is omitted, the default value (+) is applied.

python calc_tool.py 10 5

Output:

Result: 10.0 + 5.0 = 15.0

3. Execution with Options

Specify the operator using the option argument --operator (or short option -o).

python calc_tool.py 10 5 --operator "*"

(Recommended to enclose * in quotes as it may be expanded as a wildcard by the shell)

Output:

Result: 10.0 * 5.0 = 50.0

4. Error Handling (Type Mismatch or Invalid Choice)

Passing a non-numeric value or an operator not included in choices automatically results in an error.

python calc_tool.py 10 abc

Output:

usage: calc_tool.py [-h] [--operator {+,-,*,/}] num1 num2
calc_tool.py: error: argument num2: invalid float value: 'abc'

Summary

  • The standard library argparse is very convenient for handling command-line arguments.
  • Simply create an ArgumentParser and define arguments with add_argument to automate type conversion, input checking, and help generation.
  • You can create user-friendly tools by properly using mandatory “Positional Arguments” and optional “Option Arguments.”
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次