Alex Rivera | Logout

How can I read and process (parse) command line arguments?

Asked 2009-06-17T22:38:30.157
845

In Python, how can we find out the command line arguments that were provided for a script, and process them?


Related background reading: What does "sys.argv[1]" mean? (What is sys.argv, and where does it come from?). For some more specific examples, see Implementing a "[command] [action] [parameter]" style command-line interfaces? and How do I format positional argument help using Python's optparse?.

Edit
Report

2 Answers

54

One way to do it is using sys.argv. This will print the script name as the first argument and all the other parameters that you pass to it.

import sys

for arg in sys.argv:
    print arg
answered 2009-06-17T22:43:08.573
20

I use optparse myself, but really like the direction Simon Willison is taking with his recently introduced optfunc library. It works by:

"introspecting a function definition (including its arguments and their default values) and using that to construct a command line argument parser."

So, for example, this function definition:

def geocode(s, api_key='', geocoder='google', list_geocoders=False):

is turned into this optparse help text:

    Options:
      -h, --help            show this help message and exit
      -l, --list-geocoders
      -a API_KEY, --api-key=API_KEY
      -g GEOCODER, --geocoder=GEOCODER
answered 2009-06-18T04:07:57.923

Your Answer