views:

144

answers:

5

I'm just beginning to learn python and the program I'm writing requires parameters for it to run with a specific task. For example (programs name is Samtho)

samtho -i Mozilla_Firefox

How can I do that?

+9  A: 

Read the documentation on optparse. It is very powerful and will let you lots of parameters and create the help text.

unholysampler
+6  A: 

You can use the modules optparse and getopt from the standard library. The former is more flexible and thus recommended.

If you want to write your own parser, then you'll have to inspect the contents of sys.argv. sys.argv[0] contains the name of the program being executed. sys.argv[1:] is a list containing all arguments passed to the program.

This is a minimal example using optparse (I mimicked program execution by manually setting sys.argv):

>>> import sys
>>> sys.argv = 'samtho -i Mozilla_Firefox'.split()
>>>
>>> from optparse import OptionParser
>>> parser = OptionParser()
>>> parser.add_option("-i")
<Option at 0xb7881b4c: -i>
>>> options, args = parser.parse_args()
>>> options
<Values at 0xb788958c: {'i': 'Mozilla_Firefox'}>
>>> options.i
'Mozilla_Firefox'
Stephan202
+2  A: 

Use sys.argv to grab input arguments directly (import sys first). There are a bunch of different libraries (optparse and getopt builtin modules are popular) to help parse the arguments but doing raw matching might be easier depending on what complexity you need.

fengb
A: 

if you don't mind venturing from the standard library, argparse is generally considered best-in-breed for parameter parsing.

Autoplectic
A: 

I find optfunc the easiest library to use.

import optfunc, sys

def samtho(i=''):
    "Usage: %prog -i <option>"
    print i

if __name__ == '__main__':
    optfunc.run(samtho)
John Keyes