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

Copy

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

Copy

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

Copy


4. Multiple Positional Arguments

Copy


5. Argument Type Conversion

Copy


6. Argument Choices for Limited Values

Copy


7. Mutually Exclusive Arguments

Copy


8. Help and Usage Information

Copy

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


9. Subcommands for CLI

Copy


10. File Argument Parsing

Copy


Last updated 3 months ago

Last updated