How do you create a basic command-line argument parser using argparse?
Short answer
Instantiate argparse.ArgumentParser(), call add_argument() for each expected argument, then call parse_args() to parse sys.argv and return a Namespace object with the parsed values as attributes.
Advertisement
AModel answer
Instantiate argparse.ArgumentParser(), call add_argument() for each expected argument, then call parse_args() to parse sys.argv and return a Namespace object with the parsed values as attributes.
import argparse
parser = argparse.ArgumentParser(description="Greet a user")
parser.add_argument("name", help="Name of the person to greet")
args = parser.parse_args()
print(f"Hello, {args.name}!")
# python greet.py Sam -> "Hello, Sam!"Real-world example
Building a simple CLI script that greets a user by name, passed as a positional command-line argument.
Likely follow-ups
- What happens automatically if the user runs the script without providing the required 'name' argument?
Related topics