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

Recommended Python Training – Treehouse

Treehouse For Python training, our top recommendation is Treehouse.

Treehouse is an online training service that teaches web design, web development and app development with videos, quizzes and interactive coding exercises.

Treehouse has beginner to advanced Python training that programmers of all levels benefit from.



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.