4
Posted October 21, 2009 by Spyros in Python Programming
 
 

How to Use Command Line Arguments in Python

python_logo_without_textsvg
python_logo_without_textsvg

From the very first programs that you create using Python, you may notice that you really need to specify some arguments right before your program executes. For instance, say that you have created a program and you need to get some input from the user. For the sake of this tutorial, we will be creating a simple Python program grabbing two arguments from the command line, adding them together and then producing us with the result. The simplest way to do it is using the standard sys.argv. One other more sophisticated option is the getopt function. For case of simplicity and because most people tend to use simple scripts, we will be using sys.argv here. For more information on the getopts way, please refer here.

The sys.argv way

import sys

if (len(sys.argv) > 2):
    result = int(sys.argv[1]) + int(sys.argv[2])
    print result
else:
    print "Not enough Command Line Arguments !"

What happens here is very easy. First of all, we use the sys module in order to ensure cross compatibility of the arguments parsing through the various operating systems. Sys.argv is just an array holding the command line arguments of our program. Therefore, if we create this one in a file named like “args.py” and execute it using the command :

python args.py 1 2

We will get a sys.argv array with contents like : [args.py, 1, 2]. Therefore, sys.argv[0] = ‘args.py’, sys.argv[1] = ‘1’ and so on. If the command line arguments are less than 3 in this example, we inform the user that the arguments are not just enough for the program to run. If this is not the case, we add sys.argv[1] and sys.argv[2] and get our wanted result which is the addition of the two integers. Note the usage of int() casting. If we hadn’t used that, we would get 12 instead of 3, which would just be the string addition of the two arguments.


Spyros