How to Build a Simple argparse CLI in Python

Build a beginner-friendly command-line tool with argparse that greets a user, with optional greeting text and uppercase output.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

17 lines
Python 3.9+
import argparse

def greet(name, greeting="Hello", uppercase=False):
    message = f"{greeting}, {name}!"
    if uppercase:
        message = message.upper()
    return message

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Simple CLI greeting tool")
    parser.add_argument("name", help="Name of the person to greet")
    parser.add_argument("-g", "--greeting", default="Hello", help="Greeting word")
    parser.add_argument("-u", "--uppercase", action="store_true", help="Print in uppercase")
    args = parser.parse_args()

    result = greet(args.name, args.greeting, args.uppercase)
    print(result)

Output

stdout
$ python cli.py Alice
Hello, Alice!

$ python cli.py Alice -g Hi
Hi, Alice!

$ python cli.py Alice -u
HELLO, ALICE!

$ python cli.py --help
usage: cli.py [-h] [-g GREETING] [-u] name

Simple CLI greeting tool

positional arguments:
  name                  Name of the person to greet

options:
  -h, --help            show this help message and exit
  -g GREETING, --greeting GREETING
                        Greeting word
  -u, --uppercase       Print in uppercase

How it works

The argparse module reads command-line arguments and validates them automatically. add_argument defines each expected input; store_true converts a flag into a boolean True when present. The if __name__ == "__main__" guard ensures parsing only runs when the script is executed directly, keeping it importable. parse_args() returns a Namespace, and the code accesses arguments as attributes. Printing inside __main__ keeps the function clean and testable.

Common mistakes

  • Forgetting the `if __name__ == "__main__"` guard, which breaks imports.
  • Using `action="store"` for boolean flags instead of `store_true`.
  • Assuming `args.greeting` always exists without setting a default.
  • Not including `help` text, making the CLI confusing for users.

Variations

  1. Use `choices=["hello", "hey"]` on the greeting argument to restrict inputs.
  2. Make `name` optional with `nargs="?"` and a default value.
  3. Add a `--version` action to print the script version.

Real-world use cases

  • A devops script that greets users at login with configurable messages.
  • A simple deployment tool that accepts environment and verbose flags.
  • An internal reporting script that greets a team and formats output for logs.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.