Oct. 14, 2012

Command line arguments (sys.argv)

They sys module in Python is one of many available modules of library code.

What is sys.argv?

sys.argv is the list of commandline arguments passed to the Python program. argv represents all the items that come along via the commandline input, it's basically a an array holding the command line arguments of our program. Don't forget that the counting starts at zero (0) not one (1).

How do I use it?

To use it, you will first have to import it (import sys) The first argument, sys.argv[0], is always the name of the program as it was invoked, and sys.argv[1] is the first argument you pass to the program. It's common that you slice the list to access the actual command line argument:
import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)
This is an example on how to read the argument from the command line
import sys
for x in sys.argv:
     print "Argument: ", x
len(sys.argv) , checks how many arguments that have been entered. 

len(sys.argv) != 2 just checks whether you entered at least two elements
import sys
if len (sys.argv) != 2 :
    print "Usage: python ex.py "
    sys.exit (1)

To run it, simple type:

>python ex.py
Argument:  ex.py

>python ex.py hello
Argument:  ex.py
Argument:  hello

>python ex.py hello world
Argument:  ex.py
Argument:  hello
Argument:  world


Read more about: