Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 929
Homunculus Reticulli Avatar asked Jul 20 '26 00:07

Homunculus Reticulli


2 Answers

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

like image 75
Chris Avatar answered Jul 22 '26 14:07

Chris


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)
like image 26
soField Avatar answered Jul 22 '26 14:07

soField