3

I am relatively new to python. I want to write a script and pass it parameters like this:

myscript.py --arg1=hello --arg2=world

In the script, I want to access the arguments arg1 and arg2. Can anyone explains how to access command line parameters in this way?

Homunculus Reticulli
  • 65,167
  • 81
  • 216
  • 341
  • 3
    see answers to http://stackoverflow.com/questions/1009860/command-line-arguments-in-python – oob Dec 20 '11 at 21:42

4 Answers4

5

Argparse is part of the standard library (as of versions 2.7 and 3.2). This is the module I use to handle all my command line parsing although there is also optparse (which is now deprecated) and getopt.

The following is a simple example of how to use argparse:

import sys, argparse

def main(argv=None):

    if argv is None:
        argv=sys.argv[1:]

    p = argparse.ArgumentParser(description="Example of using argparse")

    p.add_argument('--arg1', action='store', default='hello', help="first word")
    p.add_argument('--arg2', action='store', default='world', help="second word")

    # Parse command line arguments
    args = p.parse_args(argv)

    print args.arg1, args.arg2

    return 0

if __name__=="__main__":
    sys.exit(main(sys.argv[1:]))

Edit: Note that the use of the leading '--' in the calls to add_arguments make arg1 and arg2 optional arguments, so I have supplied default values. If you want to program to require two arguments, remove these two leading hypens and they will become required arguments and you won't need the default=... option. (Strictly speaking, you also don't need the action='store' option, since store is the default action).

Chris
  • 44,602
  • 16
  • 137
  • 156
  • your getopt link is broken. i tried to edit but the change was only 1 character :) – oob Dec 20 '11 at 21:57
  • why do you use `sys.exit(...)` instead of just `main(sys.argv[1:])`? – matt wilkie Mar 09 '12 at 19:03
  • @mattwilkie Have a look at the [documentation](http://docs.python.org/library/sys.html#sys.exit). Basically doing this allows me to pass a return status back to the shell, which typically indicates whether or not the script was run succesfully. Also, calling `sys.exit` causes some clean up actions to be performed, such as any `finally` clauses on `try` statements. – Chris Mar 09 '12 at 19:17
2

http://docs.python.org/library/argparse.html#module-argparse

simple example can help

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
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)
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237
soField
  • 2,536
  • 9
  • 36
  • 44
1

Check out the argparse module included with the standard library. It makes this stuff a breeze once you get used to it, and it is very robust. Here is a tutorial. It is recommended to use this rather than the optparse or getopt modules.

If you don't want use the module but still want to access the arguments, check out the sys module. You will want to look at sys.argv.

oob
  • 1,948
  • 3
  • 26
  • 48
  • +1 For the link to the Doug Hellmann tutorial - it is a very useful introduction to argparse. – Chris Dec 20 '11 at 21:59
1

Python supplies 3 different ways of parsing command line arguments, not including any you write yourself using raw access to the parameter list.

http://docs.python.org/dev/whatsnew/2.7.html#pep-389-the-argparse-module-for-parsing-command-lines

The argparse module for parsing command-line arguments was added as a more powerful replacement for the optparse module.

This means Python now supports three different modules for parsing command-line arguments: getopt, optparse, and argparse. The getopt module closely resembles the C library’s getopt() function, so it remains useful if you’re writing a Python prototype that will eventually be rewritten in C. optparse becomes redundant, but there are no plans to remove it because there are many scripts still using it, and there’s no automated way to update these scripts. (Making the argparse API consistent with optparse‘s interface was discussed but rejected as too messy and difficult.)

In short, if you’re writing a new script and don’t need to worry about compatibility with earlier versions of Python, use argparse instead of optparse.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622