How to Create a Simple Python CLI with argparse

Build a beginner-friendly command-line tool with argparse that accepts positional and optional arguments to greet users flexibly.

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

Python code

32 lines
Python 3.9+
import argparse

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

def main():
    parser = argparse.ArgumentParser(
        description="A simple CLI tool that greets users."
    )
    parser.add_argument(
        "name",
        type=str,
        help="Name of the person to greet"
    )
    parser.add_argument(
        "-g", "--greeting",
        default="Hello",
        help="Custom greeting word (default: Hello)"
    )
    parser.add_argument(
        "-u", "--uppercase",
        action="store_true",
        help="Convert output to uppercase"
    )

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

if __name__ == "__main__":
    main()

Output

stdout
$ python greet.py Alice
Hello, Alice!

$ python greet.py Bob --greeting Hi
Hi, Bob!

$ python greet.py Charlie -u
HELLO, CHARLIE!

How it works

The argparse module provides a clean interface for defining and parsing command-line arguments. By using add_argument, you specify both positional arguments like name and optional flags with short (-g) and long (--greeting) forms. The store_true action automatically sets a boolean flag to True when present, which makes the uppercase option easy to check later. The parse_args() method returns a Namespace object, giving you attribute-style access to each argument via args.name and args.greeting. Finally, the __name__ == "__main__" guard ensures main() only runs when the script is executed directly, not when imported as a module.

Common mistakes

  • Forgetting that `args.greeting` has a default value, so the function gets called with 'Hello' if no flag is passed
  • Using `action='store_false'` when you want a true-flag pattern, which can flip the logic upside down
  • Omitting the `__name__ == "__main__"` guard and having side effects on import

Variations

  1. Add `type=int` to positional arguments for numeric values, and `choices=` to restrict valid inputs
  2. Use `nargs='+'` to accept multiple positional values, like a list of names

Real-world use cases

  • Creating a deployment script that takes environment and service names as CLI arguments.
  • Building a data-report generator where users pass in a date range and output format flags.
  • Writing a log-analysis tool that accepts file paths and an optional verbose verbose mode.

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.