Java Certification Training Course
- 47k Enrolled Learners
- Live Class
Python supports the creation of programs that can be run on the command line, complete with command-line arguments. It provides a getopt module, with which command-line options and arguments can be parsed.
The Python sys module provides access to any of the command-line arguments via sys.argv. It solves two purposes:
You can execute Python in this way:
$python Commands.py inp1, inp2 inp3
In Python, if a script is invoked from a shell, the arguments will be placed after the name of the script. Here the arguments will be separated by spaces and within the script those arguments will be accessible via list variable sys. argv.
print ‘Number of arguments:’, len (sys.argv), ‘arguments.’
print ‘Argument List:’, str(sys.argv)
It will produce the following output:
Number of arguments: 4 arguments.
Argument List: [‘sample.py’, ‘inp1’, ‘inp2’, ‘inp3’]
Note: One thing to remember here is that indentation and spacing is extremely important, otherwise it may give error or incorrect number of arguments.
Got a question for us? Mention them in the comments section and we will get back to you.