Updated May 3, 2023
Introduction to Python Command-line Arguments
Python command-line argument parameters are the arguments that are presented in the operating system’s command-line shell after the program’s name. Python has a number of methods for dealing with these arguments. The sys module contains methods and variables for manipulating many aspects of the Python runtime. This module gives access to several interpreter variables and functions. sys.argv, a basic list structure, is one of these variables.
There are many different ways in which a program can accept inputs from the user. The common way in Python Command-line Arguments is the input() method.
name=input("enter your name")
print('Hey',name)
=== RESTART:C:/Users/hp/AppData/Local/Programs/Python/Python37-32/demo.py ===
enter your name John
Hey John
Another way to pass input to the program is Command-line arguments. Almost every modern programming language support command line arguments. In a similar fashion, python does support command line arguments. It’s a very important feature as it allows for dynamic inputs from the user. In a command-line argument, the input is given to the program through a command prompt rather than a python script like input() method shown above.
Options available in Command-line Argument
Python 3 supports four different ways to handle command-line arguments.
- sys module
- getopt module
- argparse module
1. sys module
This is the basic and oldest method to handle command-line arguments in python. It has a quite similar approach as the C library argc/argv to access the arguments. sys module implements the command line arguments through list structure named sys.argv argv is the internal list structure which holds the arguments passed in command prompt
sys à module name
argv à list to handle dynamic inputs from the user
argv[0] à python filename
argv[1] àargument 1
argv[2] à argument 2
argv[3] à argument 3
and so on.
Steps:
- Write a python program
- Save the python program as <program name>.py extension
- Open a command prompt and change the directory to the python program path
- Use the below command to execute the program
py < python file.py > < arg1 > < arg2 > < arg3 >
Example: py demo.py 10 20 30 40 50
The first item in argv list i.e argv[0] is the python file name à in this case demo.py
argv[1] is the first argument à 10
argv[2] is the second argument à 20
argv[3] is the third argument à 30 and so on
By default, the type of argv is “String” so we have to typecast as per our requirement.
Code:
# Importing argv from sys module
from sys import argv
# type of argv
print('type of argv is :',type(argv))
# first element is the file name
print('first argument of argv :',argv[0])
# printing the complete argv list
print("argv list is :",argv)
# traversing through the list : method 1
for x in argv:
print('Argument',x)
# traversing through the argv list : method 2
for i in range(len(argv)):
print('Argument',(i+1),'-->',argv[i])
Output:
Sum of numbers passed through input():
Code:
sum_num=0
# getting input from the user
a=int(input('Enter value for a '))
b=int(input('Enter value for b '))
c=int(input('Enter value for c '))
# calculating sum of numbers
sum_num+=a+b+c
# displaying sum of numbers
print("Sum of entered numbers is :",sum_num)
This is the basic way of calculating some numbers entered by the user. Arguments in the program are accepted through input() method which then is typecast to integer type as input() returns string type data.
Output:
Calculating some of the numbers entered through command prompt:
Code:
# importing argv from sys module
from sys import argv
sum_num=0
# traversing through the list elements skipping the first element(filename)
for i in range(1,len(argv)):
sum_num+=int(argv[i])
print("sum of numbers entered is:",sum_num)
Output:
Explanation: sys.argv is imported. Then for loop is being used to traverse the argv list to calculate the sum of command-line arguments. Since arguments are of string type they are the first typecast to integer type before sum operation. The result is then printed as shown in the screenshot above.
2. getopt module
The second approach in python to implement command-line arguments is by using the getopt module. Python getopt module is similar to that of the C getopt() function for parsing command line parameters.
getopt module provides two functions and an exception to facilitate command-line argument parsing.
getopt.getopt(args,UNIX options, [long_options or gnu options])
args arguments list to be parsed
unix options “ho:v”
gnu options long options parameter ["help", "output=", "verbose"]
Code:
# importing standard libraries
import getopt
import sys
# extracting command line arguments excluding file name
argv = sys.argv[1:]
# parsing the argument list
try:
opts, args = getopt.getopt(argv, 'ho:v')
print(opts)
print(args)
except getopt.GetoptError:
print('Something went wrong!')
sys.exit(2)
Output:
Explanation: Standard libraries are imported. Sys module for getting command-line arguments and getopt module for parsing of command-line arguments. Extracting arguments from argv by excluding argv[0] i.e file name. Parsing the arguments using getopt.getopt(). Arguments with corresponding values are stored in two variables named as opts and args
3. argparse module
Python argparse module is the most preferred way to parse command-line arguments as it provides a lot of options such as positional arguments, the default value for arguments, help message, etc.
Code:
import argparse
parser = argparse.ArgumentParser()
args = parser.parse_args()
The first argparse module is imported. Then an object of argparse.ArgumentParser() is created.
While executing the above program on command prompt, nothing happens when we don’t provide any input. But when we give optional help parameter has input we get the below output
Output:
There are two types of arguments supported by argparse:
- Positional arguments
- Optional arguments
Code:
# importing argparse module
import argparse
# creating parser object
parser = argparse.ArgumentParser()
# adding positional arguments
parser.add_argument("num1",help='number 1')
parser.add_argument("num2",help='number 2')
parser.add_argument("op",help='operation')
args = parser.parse_args()
# type cast the arguments as default is string type
n1=int(args.num1)
n2=int(args.num2)
print("first number",n1)
print("second number",n2)
result=None
if args.op == 'add':
result = n1 + n2
elif args.op == 'sub':
result = n1 - n2
elif args.op == 'mul':
result = n1 * n2
elif args.op == 'div':
result = n1 / n2
else :
result = 'unsupported operation'
print("result of operation",args.op,'is :',result)
Output:
Python command-line arguments examples – How to Pass
- The below example shows the use of the argparse method.
Code:
import argparse
parser = argparse.ArgumentParser ()
parser.parse_args ()
- By using argparse method we have passing and adding help message descriptions are as follows.
Code:
import argparse
parse = "Message description"
parser = argparse.ArgumentParser(description = parse)
parser.parse_args ()
- The below example shows define optional values by using command-line arguments are as follows.
Code:
import argparse
py = argparse.ArgumentParser()
py.add_argument ("-o", "--op", help = "Show op")
args = py.parse_args ()
if args.op:
print("Output is: % s" % args.op)
Conclusion
That’s all the different ways to read and parse command line arguments in python. It’s up to the user to decide which is best for their specific requirements.
Recommended Articles
This is a guide to Python Command-line Arguments. Here we discuss an introduction, options, and How to pass python command-line arguments with examples. You can also go through our other related articles to learn more –