Python is a high-level language that is designed for doing general codes and not for any specific problem. We can utilize it for general purposes like making websites using python or analyzing the data using this python language. The “Python” programming also provides the command_line arguments. The Command Line Arguments are those arguments that we have given on the console or terminal of any operating system after mentioning the name of the code file along with the file extension. We can also define it as, in any program, the value which is passed through the command prompt which is said to be Command Line Arguments. In this guide, we will discuss the command line argument in “Python” programming.
Methods for Command Line Arguments in Python
We will explain all methods in detail in this guide and also show the practical demonstration of all those methods.
Example # 01: By sys.argv Method
We are doing these python codes in the “Spyder” app. We can access command line variables and functions by importing the system. So, we import “sys” and then we declare and initialize the “num” variable with the “len(sys.argv)”. The “argv” is going to be the list of string values that are the arguments that our command line will become. “len” represents the length of the arguments which are passed. So, in the “num” variable the number of the values passed on the terminal as the command line is stored.
We also display those argument numbers which are passed by utilizing the “print”. Below this, we put the “sys.argv[0]” in the print statement. The “argv” always holds the program name or code file name. So, the name of the file we created will be rendered on the terminal. After this, we print those arguments which are passed on the terminal. It will print all numbers which we have passed as the command line arguments on the console screen.
Below this, we have defined a for loop and declared a variable “a” there whose range is between “1” to the length of the argv which is stored in “num”. Print all arguments on the console. “argv[a]” holds all the command_line arguments. It also displays them on the console. Now, we are initializing “sum” because we want to calculate the sum of all values which we will pass at the time of execution on the terminal.
We again utilize the “for” loop and pass the range. But this time, we are calculating the sum of all those values which we have passed on the terminal. This sum will be stored in the “sum” variable. Then, we also print the sum of all values which we will pass at the time of execution on the terminal.
num = len(sys.argv)
print("Total arguments passed here :", num)
print("\nName of Python file:", sys.argv[0])
print("\nArguments which we have passed:", end = " ")
for a in range(1, num):
print(sys.argv[a], end = " ")
Sum = 0
for i in range(1, num):
Sum += int(sys.argv[i])
print("\n\nThe sum of arguments passed : ", Sum)
On the terminal, we first put the “run” keyword. Then, place the file name along with the proper extension and pass the command line arguments here. So, it displays all lines as we have defined in the code above. It first renders the length of the command line arguments then the name of the file. After this, it renders all command line arguments and also renders the sum of all of them.
Example # 02: By argparse Method
Now, we are utilizing the “argparse” method in this example. We first import the “argparse”. So, we will access the variables and function of this. We initialize a “data” variable and store a line which we will utilize in our code. After this, we are initializing a “parser” and in “description” we pass the “data” variable in which we have stored the message that we want to display and we put all these in the “my_parser” variable. We also put the “parse.args()” at the end.
data = "We are utilizing argparse method here"
my_parser = argparse.ArgumentParser(description = data)
my_parser.parse_args()
Look at the outcome below. When we pass “-h” as the command line argument it first renders the message which we have stored in the “data” variable and also shows the “optional argument” as this “h” shows the help message. When we put “-o” as the command line argument, it renders an error message that it is an unrecognized argument.
Example # 03: By getopt Method
Here is the last method which we are utilizing in this code. We are importing “sys” as well as “getopt” in this code. This “getopt” is the parser that we have utilized for the command line arguments. Then, in the “argumentList” variable, we have passed the “sys.argv[1:]” to remove the first argument that we are passing in the command line. We initialize the “my_option” with the “hmo:”.
After this, we are initializing the “my_long_option” variable. We utilize the “try” here which will check the error. After this, we are parsing the arguments. The “getopt” offers both short as well as long options, along with the option to designate a value. After this, we are checking all the arguments that we will pass as command line arguments. If the command line argument is “-h” or “–Help”, it will print the message which is given below this. If the command line argument is “-m” or “—My_file”, it will display the message which is written after this.
Also, if the command line argument is “-o” or “–Output”, it also displays the message which we have written here after this. If the command line argument is not from all of the above, it will display the error message as we have placed the “getopt. error” in the code.
argumentList = sys.argv[1:]
my_options = "hmo:"
new_long_options = ["Help", "My_file", "Output="
try:
arguments, values = getopt.getopt(argumentList, my_options, new_long_options)
for my_Argument, my_Value in arguments:
if my_Argument in ("-h", "--Help"):
print ("Displaying Help")
elif my_Argument in ("-m", "--My_file"):
print ("Displaying file_name:", sys.argv[0])
elif my_Argument in ("-o", "--Output"):
print (("Enabling special output mode (% s)") % (my_Value))
except getopt.error as err:
print (str(err))
Here you see that when we put “-h” as the command line it displays the same message which we have written in the code. When we put two command line arguments as “–Help” and also “-m”, it displays two messages below. In the “-o” command line argument, we have also passed the string which is also displayed in the message.
Conclusion
We have provided this guide to help you learn the concept of “command line arguments” in “Python”. We have explored the “command line argument” and also explained three methods here. We have explained the command line argument that the process of passing the values to the program along with the program name by the time of execution through the command prompt.