Command Line Arguments

Command Line Arguments
  • The Arguments which are passing at the time of execution are called Command Line Arguments.
  • argv is not Array it is a List. It is available sys Module.
/home/ashok/python$ py test.py 10 20 30

Here 10, 20 and 30 are the command line arguments.

Within the Python Program this Command Line Arguments are available in argv. Which is present in SYS Module.

Command line arguments

argv[0] represents Name of Program. But not first Command Line Argument. argv[1] represent First Command Line Argument.

E.g

from sys import argv
print(“The Number of Command Line Arguments:”, len(argv))
print(“The List of Command Line Arguments:”, argv)
print(“Command Line Arguments one by one:”)
for x in argv: 
   print(x)
/home/ashok/python$ py test.py 10 20 30
The Number of Command Line Arguments: 4
The List of Command Line Arguments: [‘test.py’, ‘10’,’20’,’30’]
Command Line Arguments one by one:
test.py
10
20
30

Note

1. Usually space is separator between command line arguments. If our command line argument itself contains space then we should enclose within double quotes(but not single quotes)

from sys import argv
print(argv[1])

py test.py Ashok Kumar
Ashok

py test.py 'Ashok Kumar'
'Ashok

py test.py "Ashok Kumar"
Ashok Kumar

2. Within the Python program command line arguments are available in the String form. Based on our requirement, we can convert into corresponding type by using type casting methods.

from sys import argv
print(argv[1]+argv[2])
print(int(argv[1])+int(argv[2]))

py test.py 10 20
1020
30

3. If we are trying to access command line arguments with out of range index then we will get Error.

from sys import argv
print(argv[100])


py test.py 10 20
IndexError: list index out of range

4. In Python there is argparse module to parse command line arguments and display some help messages whenever end user enters wrong input.

input() 
raw_input()
Command Line Arguments
Scroll to top