Building Command-Line Interfaces (CLI) with Python
Posted on June 1, 2024 (Last modified on June 8, 2024) • 1 min read • 204 wordsDiscover how to build command-line interfaces (CLI) in Python using the `argparse` module, including handling arguments and options.
Command-Line Interfaces (CLI) are a powerful way to interact with your programs. This guide covers building CLIs in Python using the argparse
module, including handling arguments and options.
import argparse
parser = argparse.ArgumentParser(description="Simple CLI")
parser.add_argument("name", help="Your name")
args = parser.parse_args()
print(f"Hello, {args.name}!")
parser.add_argument("-a", "--age", type=int, help="Your age")
args = parser.parse_args()
print(f"Hello, {args.name}! You are {args.age} years old.")
Options with default values.
parser.add_argument("-g", "--greeting", default="Hello", help="Greeting to use")
args = parser.parse_args()
print(f"{args.greeting}, {args.name}!")
subparsers = parser.add_subparsers(dest="command")
# Subcommand 1
hello_parser = subparsers.add_parser("hello")
hello_parser.add_argument("name", help="Your name")
# Subcommand 2
goodbye_parser = subparsers.add_parser("goodbye")
goodbye_parser.add_argument("name", help="Your name")
args = parser.parse_args()
if args.command == "hello":
print(f"Hello, {args.name}!")
elif args.command == "goodbye":
print(f"Goodbye, {args.name}!")
parser.add_argument("-g", "--greeting", default="Hello", help="Greeting to use")
args = parser.parse_args()
print(f"{args.greeting}, {args.name}!")
parser.add_argument("-r", "--required", required=True, help="A required argument")
args = parser.parse_args()
print(f"Required argument: {args.required}")
parser.add_argument("-v", "--verbose", action="store_true", help="Increase output verbosity")
args = parser.parse_args()
if args.verbose:
print("Verbose mode is on")
Building command-line interfaces in Python with argparse
is straightforward and powerful. Practice creating CLIs with various arguments and options to enhance your programs’ usability.