
The Argparse Python is an easy way to write the command line interfaces. Command line arguments on the other hands are the values passing over when a program gets called. The Argparse Python generally deals with arguments using the sys.argv array.
In this article we will learn how to use command line options and arguments using the Argparse Python method.
All you have to do is import argparse module in Python script and then create a parser object. Now you are ready to add arguments. You can parse these arguments anytime using the .parse_args() method. Now use the parsed argument anywhere you want. For example, you want to print the name and age of a person.
| print(f"Hello, {args.name}!") if args.age: print(f"You are {args.age} years old.") if args.verbose: print("Verbose mode is enabled.") |
Let us follow a simple two to three point process to import argparse and start using it for command line options easily.
| import argparse |
| parser = argparse.ArgumentParser(description="A simple argparse example") |
| class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars=’-‘, fromfile_prefix_chars=None, argument_default=None, conflict_handler=’error’, add_help=True, allow_abbrev=True) |
| parser.add_argument("name", help="Your name") # Positional argument parser.add_argument("-a", "--age", type=int, help="Your age") # Optional argument parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose mode") |
| args = parser.parse_args() |
In Python, we can define the Command line options in Argparse Python using the argaprse method where you can specify optional arguments that users can feed while running a script.
Let us suppose we have arguments “integers” and we want to accumulate the values to perform a simple addition operation. When the script is parsed it calculates the addition of the argument values and displays the result.
| import argparse parser = argparse.ArgumentParser (description = ‘evaluate some integers.’) parser.add_argument ( ‘integers’, metavar = ‘N’, type = int, nargs = ‘+’, Help = ‘an integer is given for the accumulator’) parser.add_argument(dest = ‘accumulate’, action = ‘store_const’, const = sum, help = ‘sum of the integers’) args = parser.parse_args() print (args.accumulate(args.integers)) |
| import argparse import math parser = argparse.ArgumentParser(description="Calculate factorial of a number.") parser.add_argument("num", type=int, help="An integer whose factorial is to be calculated") args = parser.parse_args() print(f"Factorial of {args.num} is {math.factorial(args.num)}") |
| import argparse parser = argparse.ArgumentParser(description="Convert temperature between Celsius and Fahrenheit.") parser.add_argument("temperature", type=float, help="Temperature value to convert") parser.add_argument("-c", "--to-celsius", action="store_true", help="Convert to Celsius") parser.add_argument("-f", "--to-fahrenheit", action="store_true", help="Convert to Fahrenheit") args = parser.parse_args() if args.to_celsius: result = (args.temperature - 32) * 5/9 print(f"{args.temperature}°F is {result:.2f}°C") elif args.to_fahrenheit: result = (args.temperature * 9/5) + 32 print(f"{args.temperature}°C is {result:.2f}°F") else: print("Please specify conversion type with -c or -f") |
| Syntax Example | Description |
| parser.add_argument("filename") | Required argument; must be provided in order. |
| parser.add_argument("-n", type=int) | Optional argument with a short flag (-n). |
| parser.add_argument("--name", type=str) | Optional argument with a long flag (--name). |
| parser.add_argument("-v", "--verbose", action="store_true") | Flag that enables a feature when used. |
| parser.add_argument("--count", default=5, type=int) | Assigns a default if no value is given. |
| parser.add_argument("--email", required=True) | Mandatory option; script errors if omitted. |
| parser.add_argument("--age", type=int) | Converts input into specified type (e.g., int). |
| parser.add_argument("numbers", nargs="+", type=int) | Accepts multiple values as a list. |
| parser.add_argument("coords", nargs=2, type=float) | Accepts exactly two values. |
| parser.add_argument("--mode", choices=["auto", "manual"]) | Limits input to specific values. |
| parser.add_argument("-h", "--help") | Displays help documentation when run with -h. |