116. Command-Line Argument Parsing

Here are 10 Python snippets that demonstrate how to use the argparse module to parse command-line arguments and options effectively:


1. Parsing a Simple Positional Argument

Copy

import argparse

parser = argparse.ArgumentParser(description="Process a single argument.")
parser.add_argument("name", type=str, help="Your name")
args = parser.parse_args()

print(f"Hello, {args.name}!")

2. Adding an Optional Argument

Copy

import argparse

parser = argparse.ArgumentParser(description="Optional argument example.")
parser.add_argument("--age", type=int, help="Your age")
args = parser.parse_args()

if args.age:
    print(f"You are {args.age} years old.")
else:
    print("Age not provided.")

3. Using Default Values for Optional Arguments

Copy


4. Using Boolean Flags

Copy


5. Parsing Multiple Positional Arguments

Copy


6. Restricting Choices for an Argument

Copy


7. Specifying Argument Types

Copy


8. Adding Help Text and Descriptions

Copy


9. Parsing Multiple Optional Arguments

Copy


10. Grouping Arguments

Copy


How to Run These Scripts

Save the Python script and run it from the command line. For example:

Copy

Summary

The argparse module supports:

  • Positional and optional arguments.

  • Default values.

  • Boolean flags.

  • Type validation.

  • Choices for arguments.

  • Grouping arguments.

Let me know if you'd like more advanced examples or further explanation!

Last updated