+26  A: 

There are the following modules in the standard library:

  • The getopt module is similar to GNU getopt.
  • The optparse module offers object-oriented command line option parsing.

Here is an example that uses the latter from the docs:

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--file", dest="filename",
                  help="write report to FILE", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")

(options, args) = parser.parse_args()

optparse supports (among other things):

  • Multiple options in any order.
  • Short and long options.
  • Default values.
  • Generation of a usage help message.
Ayman Hourieh
Are these built in modules the best?Or can you think of a better custom way?
Yes, these are the best. Since they're part of the standard library, you can be sure they'll be available and they're easy to use. optparse in particular is powerful and easy.
Barry Wark
@edgerA: What does "better custom way" mean?
S.Lott
optparse is one of the best; getopt is old and really ought to be considered deprecated.
jemfinch
A: 

There's also optparse.

Javier Badia
+4  A: 
import sys

print "\n".join(sys.argv)

sys.argv is a list that contains all the arguments passed to the script on the command line.

ReadySquid
For really simple stuff, this is the way to go, although you probably only want to use `sys.argv[1:]` (avoids the script name).
Xiong Chiamiov
+2  A: 

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
JPCosta
+1  A: 

I like getopt from stdlib, eg:

try:
    opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError, err: 
    usage(err)

for opt, arg in opts:
    if opt in ('-h', '--help'): 
        usage()

if len(args) != 1:
    usage("specify thing...")

Lately I have been wrapping something similiar to this to make things less verbose (eg; making "-h" implicit).

Peter Ericson
+1  A: 

There is also argparse module (an "impovement" on stdlib's optparse module). Example from the introduction to argparse:

# script.py
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'integers', metavar='int', type=int, choices=xrange(10),
         nargs='+', help='an integer in the range 0..9')
    parser.add_argument(
        '--sum', dest='accumulate', action='store_const', const=sum,
        default=max, help='sum the integers (default: find the max)')

    args = parser.parse_args()
    print args.accumulate(args.integers)

Usage:

$ script.py 1 2 3 4
4

$ script.py --sum 1 2 3 4
10
J.F. Sebastian
+7  A: 

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
Van Gale
+9  A: 

Just going around evangelizing for argparse which is better for these reasons.. essentially:

(copied from the link)

  • argparse module can handle positional and optional arguments, while optparse can handle only optional arguments

  • argparse isn’t dogmatic about what your command line interface should look like - options like -file or /file are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality

  • argparse produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments.

  • argparse supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (e.g. 1, 2, or 3) be known in advance

  • argparse supports parsers that dispatch to sub-commands, while optparse requires setting allow_interspersed_args and doing the parser dispatch manually

And my personal favorite:

  • argparse allows the type and action parameters to add_argument() to be specified with simple callables, while optparse requires hacking class attributes like STORE_ACTIONS or CHECK_METHODS to get proper argument checking
Silfheed
This is now part of standard Python as of 2.7 and 3.2 :)
orange80