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.
argv represents Name of Program. But not first Command Line Argument. argv represent First Command Line Argument.
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
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) 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+argv) print(int(argv)+int(argv)) 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) 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.