Python - Command Line Argument

Card Puncher Data Processing

Python - Command Line Argument

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.

How to

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

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.





Discover More
Card Puncher Data Processing
Python - Script

in Python are source file that can be run. On Linux, begin your scripts with your interpreter. See or You can find them by executing the whereis commando: sys.argv[0] is the script name...



Share this page:
Follow us:
Task Runner