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

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

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


4. Using Boolean Flags


5. Parsing Multiple Positional Arguments


6. Restricting Choices for an Argument


7. Specifying Argument Types


8. Adding Help Text and Descriptions


9. Parsing Multiple Optional Arguments


10. Grouping Arguments


How to Run These Scripts

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

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