83. Using argparse for CLI Parsing

The argparse module in Python is used to handle command-line arguments, providing a simple way to create user-friendly CLI tools. It allows you to specify the arguments your program expects, automatically generates help and usage messages, and handles input validation.

Here are 10 Python code snippets demonstrating different uses of argparse for building command-line interfaces:

1. Basic Argument Parsing

import argparse

def main():
    parser = argparse.ArgumentParser(description="A simple command-line tool")
    parser.add_argument("name", help="Your name")
    args = parser.parse_args()
    print(f"Hello, {args.name}!")

if __name__ == "__main__":
    main()

2. Optional Arguments with Default Values

import argparse

def main():
    parser = argparse.ArgumentParser(description="Greet a user with an optional age argument")
    parser.add_argument("name", help="Your name")
    parser.add_argument("-a", "--age", type=int, default=30, help="Your age (default is 30)")
    args = parser.parse_args()
    print(f"Hello, {args.name}, you are {args.age} years old!")

if __name__ == "__main__":
    main()

3. Boolean Flag Argument


4. Multiple Positional Arguments


5. Argument Type Conversion


6. Argument Choices for Limited Values


7. Mutually Exclusive Arguments


8. Help and Usage Information

You can run this script with the --help flag to see the description and usage.


9. Subcommands for CLI


10. File Argument Parsing


These examples demonstrate how to use argparse for different tasks, such as parsing simple arguments, handling default values, and supporting more complex features like subcommands and file input.

Last updated