Welcome to our blog and a new chapter on our Python Learning series, Learn Python with me. Today in this post, we will discuss the Python Command Line Arguments in detail and in the most simplistic manner.
Find the link here to all chapters of the Python tutorial: Learn Python
What are Python Command Line Arguments?
Command Line arguments are the input values that are passed to a program from outside a program. In other words, the values which are passed from system prompt or command prompt are called Command Line arguments. For example, if you have a program with the name, subtract.py with the logic to subtract any two values and if you pass two values as mentioned below, the values you would pass then are called Command Line Arguments.
E:\>python subtract.py 32 12
Result = 20
Here in the example above, the values 32 and 12 are Command Line Arguments. You can notice that the arguments are entered with space in between from the keyboard. By default, these arguments are collected in the form of strings in a list called ‘argv‘ that is present in the sys module. Since argv is a list that includes all the values passed to the program, argv[0] refers to the name of the program, argv[1] refers to the first value, and argv[2] refers to the second value. Consider the diagram below to understand this concept better.
If you want to find the number of command-line arguments in a program, you can use the len() function for the same. Let us have a look at an example now.
import sys
number=len(sys.argv)
arguments=sys.argv
print("Number of arguments: ",number)
print("The arguments of this program are",arguments)
print("Let us look at the arguments one by one")
for i in arguments:
print(i)
Output
E:\Python\CommanLineArguments> python CommandLineExample.py 32 i-Sapna Blog YouTube 150000000
Number of arguments: 6
The arguments of this program are ['CommandLineExample.py', '32', 'i-Sapna', 'Blog', 'YouTube', '150000000']
Let us look at the arguments one by one
CommandLineExample.py
32
i-Sapna
Blog
YouTube
150000000
You can also add the numbers you pass as arguments and obtain sum as mentioned in the program below
import sys
total=int(sys.argv[1])+int(sys.argv[2])
print("Total= ",total)
Output
E:\Python\CommanLineArguments> python CommandLineExample.py 30 40
Total= 70
Parsing Command-Line Arguments in Python
You can build user-friendly programs using the argparse module in Python. The help and usage messages are automatically generated using this argparse module if invalid arguments are entered by the user. It also guides users with relevant messages when an error occurs. To implement the argparse module we should import it to our program using as mentioned below.
import argparse
After importing as mentioned above, you have to create an object of ArgumentParser class object with the description of the program as mentioned below.
parser=argparse.ArgumentParser(description="This program shows the square value of given number")
If you don’t want to display the help on this program, you can skip this step and create the object as mentioned below.
parser=argparse.ArgumentParser()
The next step would be to add arguments with the add_argument() method as mentioned below.
parser.add_argument("number",type=float, help="Please enter float type number.")
In the code mentioned above, the number refers to the variable in which the argument will be stored. type=float means that only float values are allowed to be entered. help=”Please enter float type number.” is the help text that will be displayed when the user seeks help. The arguments entered by the user are parsed by the parser. They are received by the parse_args() method as mentioned below.
args=parser.parse_args()
‘args‘ refers to an object of the ‘Namespace’ class of the argparse module. Let us look at an example below.
#program to subtract two numbers.
#save it as subtract.py
import argparse
#create ArgumentParser class object
parser=argparse.ArgumentParser(description="This program subtracts two numbers")
#add two arguments with names a1 and a2 and type as int
parser.add_argument("a1",type=int,help="Enter first number")
parser.add_argument("a2",type=int,help="Enter second number")
#get back the arguments passed to the program
args=parser.parse_args()
#convert the a1 and a2 values into int type and subtract them
result=int(args.a1)-int(args.a2)
print("The result is= ",result)
Error Output without passing arguments
E:\Python\CommanLineArguments> python subtract.py
usage: subtract.py [-h] a1 a2
subtract.py: error: the following arguments are required: a1, a2
Output when passing arguments
E:\Python\CommanLineArguments> python subtract.py 32 17
The result is= 15
Let us now write a program to take 1 or more arguments and display them as lists
import argparse
#call the ArgumentParser()
parser=argparse.ArgumentParser()
#add arguments to the parser
parser.add_argument('numbers',nargs='+')
#get back the arguments into args object
args=parser.parse_args()
#display the arguments from the list: args.numbers
for i in args.numbers:
print(i)
Output
E:\Python\CommanLineArguments> python main.py 20 i-Sapna 89.5
20
i-Sapna
89.5
We hope you have understood the concept of Python Command Line Arguments. If you are a little confused about this topic, try practising each example mentioned in this post. Also, please do not hesitate to ask your queries or share your comments in the comments section below.