This is a detailed tutorial of the Python Command Line Arguments. Learn to parse the command-line options and arguments to get their values in the program.
Python Command Line Arguments
Let’s say there’s a Python file named
hello.py and we want to execute it from the command line. We’ve to write the following command.
You can also pass any number of arguments along with this command as demonstrated in the following command.
python hello.py arg1 arg2 arg3
arg3 are the three different arguments. These arguments can be accessed within the Python program code written in the file
The command-line arguments can be handled with the Python
sys module. You can use the
argv property of the sys module to get the full list of the arguments passed while executing the current python code file.
The following code illustrates the syntax to fetch the list of arguments, number of arguments and the name of the currently executing Python file.
import sys #List of arguments sys.argv #Number of arguments len(sys.argv) #Name of the currently executing Python File sys.argv
Note. Always keep in mind that the file name itself is counted as the first argument.
We have saved the code written below in a file named
import sys print("List of Arguments: ", sys.argv) print("Number of Arguments: ", len(sys.argv)) print("Currently Executing File: ", sys.argv)
We executed the above file using the following command.
List of Arguments: ['try.py', 'hello', 'how', 'are', 'you'] Number of Arguments: 5 Currently Executing File: try.py
As you can observe in the output, the
sys.argv contains a to check the count of this list that gives us the total number of arguments. In the end, we’ve printed the first item of the list or the item at the index 0 i.e. the name of the currently executing python file.
You can use the Python For Loop to iterate the arguments list to process each of the arguments one by one.
Python Command-Line Options
We have learned how you can get all of the different arguments and now let’s figure out the same about the command-line options. One command-line option basically comprises of two command-line arguments. Observe the following command.
Here in the above command, there are five command-line arguments but there are only two command-line options. The five command-line arguments are
value2. On the other hand side, the two options are
opt2 with values
To get the values for the different options, you can first fetch the list of all of the argument using sys.argv[1:] and then can process this list using the
getopt module to fetch the option values.
This module can be used to get the values of the different options for the currently executing python file. All you need to do is to import the
getopt module and then further have to use its method which is also named
getopt.getopt(args, options, [long_options])
This method can take upto three different arguments that are described below.
- args. This is a Python list that contains the list of arguments. We can pass here the list retrieved using
sys.argv[1:]. Make sure the list that you are passing here should not contain the file name as the argument. This list of arguments should contain single-character options. For example, a, b, c, etc. For long options, use the third argument.
- options. This is the string of options for which we want to get the values. Multiple option names have to be separated by a
:(colon) symbol. For example,
- [long_options]. This is an optional argument and should belong to list data type. This is for the options with more than one character. For example, option1=, opt1=, some-option=, etc. These options are always followed by an equal sign (=).
getopt() returns a value that further consists of two different values. The first value is basically a list of tuples. Each of these tuples contains the
(option, value) pair. The second value returned by this method is also a list that contains the arguments that are still left after parsing the recognizable options and getting their values.
Have a look at the following code.
import sys, getopt argumentsListIncludingFileName = sys.argv argumentsListExcludingFileName = argumentsListIncludingFileName[1:] optionsString = "a:b:c:" optionANDvalues, remainingArguments = getopt.getopt(argumentsListExcludingFileName, optionsString) print(optionANDvalues) print(remainingArguments)
We saved the above code in a file named try.py and executing it using the following command.
[('-a', 'VALUE_A'), ('-b', 'VALUE_B'), ('-c', 'VALUE_C')] ['hello', 'how', 'are', 'you']
Each tuple in the list of option-value pairs contains the option name itself prepended with
- at the first position and the value of it in the second position. Also, the remaining arguments are also printed in the second line.
The following example illustrates the mixed usage of short and long options.
import sys, getopt argumentsListIncludingFileName = sys.argv argumentsListExcludingFileName = argumentsListIncludingFileName[1:] optionsString = "i:o:" longOptionsList = ["opt1=", "some-option="] optionANDvalues, remainingArguments = getopt.getopt(argumentsListExcludingFileName, optionsString, longOptionsList) print(optionANDvalues) print(remainingArguments)
We ran the above code saved in
try.py file using the following command.
[('-i', 'VALUE_i'), ('-o', 'VALUE_o'), ('--opt1', 'VALUE_opt1'), ('--some-option', 'VALUE_some_option')] ['hello', 'how', 'are', 'you']
This is the exception raised in case the method finds an unrecognized option and when no argument is given while the option requires one. The argument passed to the exception is basically a string that contains the reason for why the exception raised. Its attributes
opt gives further information about the exception.
You can handle such exceptions using Try Except.
I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.