Python is an interpreted language based on object oriented programming. It is very powerful, highly interactive, and can easily be integrated with user programs in C or other languages. Even if you have no prior programming experience, you can learn Python quite fast, and easily use Python to create your own web programs, or even develop your own games.
In this tutorial we explore command line arguments and understand how to use them in Python programs.
Basic command line arguments
First, let’s understand what a command line argument is. For beginners, who have no exposure to programming, command line arguments are what we type at the command line prompt along with the script name while we try to execute our scripts. Python like most other languages provides this feature. For instance, let’s assume we are working on a unix based system. The “>” in the examples below symbolizes the command prompt on the terminal. To explain command line arguments, we will make use of a sample Python script “try_this.py”. For instance, the try_this.py can have the following code that is explained later in this tutorial
!#/usr/bin/python import sys print (str(sys.argv[1]) “is delicious. Would you like to try some?\n”) print (“Or would you rather have the” str(sys.argv[2]) “?\n”) if (len(sys.argv)>3 ) { print “Usage details: try_this.py <input1> <input2>” sys.exit }
We can execute the try_this.py script as is without any other input like below
> try_this.py
Or we can decide to write something along with the script name try_this.py, like this –
>try_this.py apple orange
In the above example we have passed additional terms – apple and orange to the script. “try_this.py”, “apple” and “orange” are command line arguments. The script uses these arguments for as inputs for its execution. Now lets assume there are two users who execute the try_this.py script, they would get different results.
User 1 > try_this.py apple orange User 2 > try_this.py peach raisin
User1 Results
Apple is delicious. Would you like to try some?
Or would you rather have the Orange ?
User2 Results
Peach is delicious. Would you like to try some?
Or would you rather have the raisin ?
So lets take a look at what lines of code in the script enabled this. In Python, sys.argv is the list of all the command line arguments that we pass. The argv is an array that has all the entries that have been typed along with the script name. To enable this, we have to first import the method sys. We do that using the syntax import sys. If this line is not included in our script, it would cause an error while execution when we are trying to access sys.argv array.
To find the length of the sys.argv array we can use an in-built Python method len(sys.argv) to find the length of the array. The sys.argv array stores all the entries provided with the script in the command line. That is, it includes the script name as well i.e. the array in User1’s terminal will have the following contents: try_this.py, apple and orange
The script name is stored as the first array element sys.argv[0]. The other key detail that you need to note is the way we access the array elements. We use str(sys.argv[1]), the word str make this array element a string. Array elements of sys.argv can be accessed by changing the index value.
You can also use sys.exit in the code to exit if the required arguments are not passed to the script. For instance, if User3 runs the try_this.pl with three inputs instead of two, the script will exit and print the usage details.
> try_this.py apple orange peach
Results
Usage details: try_this.py <input1> <input2>
Command line options
The other command line input that can be provided is an option. Options are denoted by – or — in the command line. Here, an option is passed along with the argument. This enables the user to provide the arguments in any order they choose to, as the options would precede the arguments.
Syntax
getopt.getopt(args,options,[long options])
args the arguments as before
options the options that you want the script to recognize. The compulsory ones should be suffixed with :
long options these are options that are more descriptive than options. The compulsory ones should be suffixed with =
Example: welcome.py
import getopt,sys def main(argv): opts,args = getopt.getopt(argv,”hn:”,[“help”, “name=”] except getopt.GetoptError: print (“Usage : welcome.py –n <name> or welcome.py --name <name>”) sys.exit(2) for option arg in opts: if (opt == ‘-h’ || opt == ‘--help’) { print (“Usage : welcome.py –n <name> or welcome.py --name <name>”) } if (opt == ‘-n’ || opt == ‘-name’) { print (“Welcome to the world of Python, ”,arg) } if __name__ == “__main__” : main(sys.argv[1:])
Results
> welcome.py –h –n “Wilson”
Usage: welcome.py –n <name> or welcome.py –name <name>
Welcome to the world of Python, Wilson
>welcome.py –d
Usage: welcome.py –n <name> or welcome.py –name <name>
>welcome.py –name “Andrew “
Welcome to the world of Python , Andrew
In this example, we need to import the getopt methods with import getopt. The options provided in the script are –h and –n. Of these, the n option and its argument is compulsory and so in the definition, it is followed by :. Instead of –h and –n if the user decides to use more descriptive options, they can use the long options. Again these long options should be preceded with — in the command line and the compulsory ones should be followed by = in the definition.
If the user provides an option that has not been defined in the script, then we use getopt.GetoptError methods to issue an error and exit the script.
There are more advanced methods than these, to manage the command line arguments. These are the optparser module and argparser modules. These allow the flexibility of combining the options together, along with other more complex features.
For simple programs, you are unlikely to need command line argument deeper than this. However, if you do want to explore further, you can try out an Advance Python Programming course, or perhaps get some practise developing fun games with Python!