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.
Argparse Module In Python
The Argparse Python module handles the command line arguments and options in a structured and organised manner. It is used to simplify the process of defining and parsing the command line arguments which is then used to make scripts in programs more flexible and user friendly.
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.”) |
The command line environment gets a better companion with the argparse module.
Steps for Creating an Argparse Module In Python
Let us follow a simple two to three point process to import argparse and start using it for command line options easily.
Import Argparse In Python Program
First thing you need to do is drop an import code at the starting of the Python program to integrate or use the argparse python method.
import argparse |
Create a Parser Object
Now build a simple parser object which can parse the argument mentioned inside the brackets. You can add it using the .ArgumentParse() method easily.
parser = argparse.ArgumentParser(description=”A simple argparse example”) |
Check the simple syntax for creating a parser where you can store all the information.
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) |
Add Arguments In Parser
You can add an argument in the Parser object created in the previous step. Just use the .add_argument() method with the details to add the argument for every object.
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”) |
Parse Arguments
You can now easily parse arguments using the .parse_args() method below.
args = parser.parse_args() |
You can also use these parsed arguments in printing the arguments entities easily on the screen.
Save the Script
You will have to save the script using the .py extension file. Now you can easily run the parse argument and object from the terminal and display messages easily.
Command Line Option Using Argparse Python Method
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)) |
Factorial Using Command Line Options In Argparse Python
Let us calculate the factorial of a function using the Command line arguments in Argparse Python below using the script.
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)}”) |
Convert Temperature Between Celsius and Fahrenheit Using Command Line Options
Let us create a script to convert temperatures between the celsius scale and fahrenheit scale.
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”) |
List of Arguments Used In Command Line Options In Argparse Python
Let us check some of the frequently used arguments in Command line options in the table below.
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. |
Why Use Command Line Arguments Using Argparse Python?
When using command-line arguments in Argparse Python with argparse it makes scripts more flexible, interactive, and user-friendly. Instead of hardcoding values, users can provide inputs dynamically when executing the script, making it more reusable for different scenarios.
For example, a script that processes files, performs calculations, or fetches data can accept parameters like file names, numerical values, or flags to modify behavior, reducing the need for modifying the source code.
Another key advantage of argparse is its built-in error handling and automatic help message generation. If a user provides an incorrect argument type or misses a required option, argparse displays a clear error message, preventing unexpected crashes. Additionally, the – – help option automatically provides documentation on how to use the script. This makes Python scripts more accessible and professional, especially when shared with others or used in production environments.
Learn Python Programming with PW Skills
Become a skilled programmer in Python with Decode DSA with Python on PW Skills. Get in-depth knowledge of the programming language Python with practice exercises, module assignments, and real world projects. Learn about Command line options and Argparse Python module in this course.
Get a completely self paced course with pre-recorded tutorials on the platform. Learn about all major Python libraries and more with interactive coursework and tutorials only at pwskills.com
Argparse Python FAQs
Q1. What is the Argparse Python method?
Ans: The Argparse Python module handles the command line arguments and options in a structured and organised manner. It is used to simplify the process of defining and parsing the command line arguments.
Q2. How to fetch the command line arguments in Python?
Ans: You can easily fetch the command line arguments in Python using the sys.argv list from the sys module given in the Python library.
Q3. How to pass the command line arguments in Python?
Ans: We use argparse to pass the command line arguments in Python using the add_argument() method and them using the parse_args() method.
Q4. What are optional arguments in the Command Line?
Ans: Some optional arguments in the command line options are -v, - - verbose. Also, the optional arguments must be prefexied with a - or - - .