Go4Expert (http://www.go4expert.com/)
-   Python (http://www.go4expert.com/articles/python-tutorials/)
-   -   Reading Command Line Arguments In Python (http://www.go4expert.com/articles/reading-command-line-arguments-python-t29146/)

pradeep 26Sep2012 20:08

Reading Command Line Arguments In Python
Command line arguments are quite old, in the days of DOS they were generally just options enabling/disabling mechanism and were known as switches. But, after the growth of *nix systems command line arguments have been developed and have provided a lot of features to power users.

Here's an example of a command line argument.


[pradeep@home-desktop]$ ls -lh --color='yes'

Now, you can pass switches, values, single & multiple, it does not always need to be in a specific order, you can pass multiple arguments at once. There are two types of options, short options (are single characters), like l & h in the above sample, and long options (are more than 1 character) which are preceded by 2 hipens (-).

In this article we'll be looking at making your Python program read command line arguments.


To learn about reading command line parsing, let's first look at how Python reads command line arguments natively, it needs to be in a specific order as there is no parsing as such, just arguments that were passed from the shell. Follow the example below.

Code: Python


import sys

print 'Passed', len(sys.argv), 'arguments'
print 'Arguments -', str(sys.argv)


[pradeep@home-desktop ]$ /var/www/test/test.py Pradeep Partha
Passed 3 arguments
Arguments - ['/var/www/test/test.py', 'Pradeep', 'Partha']

Using getopt

getopt module parses the command line arguments and processes them using the config that is provided to it. getopt accepts 3 arguments, first a list of arguments that need to be parsed, next is the list of options that need to be looked for, if an option should accompany a value it should be followed by : symbol (like in the example below, option i can have a value, whereas others are just switches), and the last optional parameter is long options for the previously specified short option, they should be specified in the same order as the short options. Try the example below:

Code: Python


import sys,getopt

opts, args = getopt.getopt(sys.argv[1:], 'ai:d', ['all','input=','debug'])

for opt, arg in opts:
   print opt,"==>",arg


[pradeep@home-desktop ]$ test.py -i pradeep.txt -d --all
-i ==> pradeep.txt
-d ==>
--all ==>

In your code you can iterate the options parsed by getopt to change the behaviour of the program as per your needs.

All times are GMT +5.5. The time now is 07:20.