Homunculus Reticulli
Homunculus Reticulli

Reputation: 68436

groking command line parameters in a python script

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?

Upvotes: 3

Views: 1224

Answers (4)

Chris
Chris

Reputation: 46326

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).

Upvotes: 5

soField
soField

Reputation: 2696

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)

Upvotes: 2

Mark Ransom
Mark Ransom

Reputation: 308216

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.

Upvotes: 1

oob
oob

Reputation: 1958

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.

Upvotes: 1

Related Questions