Python - Command Line Argument

> Procedural Languages > Python > Python - Engine

1 - About

Python provides command-line arguments through the list sys.argv (from the sys module) where:

  • sys.argv[0] is the script name
  • sys.argv[n] is the argument n

Therefore len(sys.argv) is the number of command-line arguments.

3 - How to

3.1 - Get the command lines

The python file helloWorld.py:

import sys
 
print 'Hello',sys.argv[1],'!'
 
print 'List of Args:'
for (i,commandLine) in enumerate(sys.argv):
    print ' - ',i,':',commandLine

Run it with one arguments (Nico)

python helloWorld.py Nico

and you will get this output:

Hello Nico !
List of Args:
 -  0 : D:\svn_di_obieejmeter\wlst\helloWorld.py
 -  1 : Nico
Advertising

3.2 - Get the command lines with getopt

The below helloWorld.py script shows how we can parse the command line argument with the getopt module.

import sys, getopt
 
opts, args = getopt.getopt(sys.argv[1:],"hn:f:",["lastname=","firstname=","isGood"])
#   - the first argument is the argument list to be parsed, without the name script  ie . "sys.argv[1:]
#   - the second argument is a list of short option (one letter) in a string separated by a : 
#        (don'forget the last one). The h options (for hulp) doesn't need to be separeted
#   - the third argument is a list of long option name. The long option name should not include the leading 
#         '--' characters. Options which require an argument should be followed by an equal sign ('=').
 
print 'Hello ',opts[4][1],' !'
 
print 'The value of Opts is: ', opts
print 'The value of Args is: ', args

By running it with the following arguments:

>python helloWorld.py -h -n nOption -f fOption --lastname=Gerard --firstname=Nico --isGood firstArg secArg

We will get:

Hello  Nico  !
The value of Opts is:  [('-h', ''), ('-n', 'nOption'), ('-f', 'fOption'), ('--lastname', 'Gerard'),
 ('--firstname', 'Nico'), ('--isGood', '')]
The value of Args is:  ['firstArg', 'secArg']

As you can see the long option isGood doesn't has any value.