Similar to the built-in functions
input(), Python command-line arguments allow us to get input values from the user in the command prompt during the execution time of the program.
Command-line arguments in python are another way to read user inputs. The user inputs are passed as arguments in the command prompt when executing the code. Python provides built-in modules to accept the user inputs that are passed from the command prompt.
There are 2 different types of modules to accept command line arguments in Python. They are,
Let us discuss these modules in detail.
Save the below-given code in a notepad file with the name cmd.py.
from sys import * print('The command line arguments are: ') for i in argv: print(i) print("Type of argv is:",type(argv))
While executing the above code in the command prompt, pass the input values as shown in the below command.
python cmd.py FACEPrep Python
Here, FACEPrep and Python are the user input values. After execution, you will get the output as shown below.
Output: The command line arguments are: cmd.py FACEPrep Python Type of argv is: <class 'list'>
We have passed two arguments but the output is obtained with three arguments. The first argument printed in the output is the file name.
When using 'sys' module, all the command line arguments gets stored in the form of a list. By default, the file name gets stored in argv, the first user input value in argv and so on. We can also print the number of arguments using the built-in function len() as shown below.
from sys import * print("The number of arguments: ", len(argv)) print("The argument list: ", str(argv)) Output: The number of arguments: 3 The argument list: ['cmd.py', 'FACEPrep', 'Python']
Here, len(argv) gives the number of command-line arguments that have been passed from the command prompt along with the file name.
This module helps in parsing through the command-line options and arguments. There are 2 functions and an exception under this module.
This is used to parse the command line options and parameter list.
Syntax getopt.getopt(args, shortops, longopts=)
Below is an example command to pass arguments when we use getopt module.
python cmd.py hello --caps kyle Output HELLO, KYLE!
The option -caps convert the argument list into capital letters.
This is similar to the above function, but the GNU style scanning mode is used by default which means that the option and non-option arguments can be intermixed.
Syntax getopt.gnu_getopt(args, shortopts, longopts=)
This exception is raised when an option in the argument list is not recognizable or when an option that requires an argument is left empty.