开发者

Order of command line arguments in a Python script

Let's say I have the following script.

This script finds the largest file under /home and emails the output with the 10 largest files.

./myscript.py -d /home -e joe@email.com -p 10

Let's say I don't want it to email me, I remove "-e joe@email.com" The script fails because it's expecting "-e" to be present. I'm assigning the variables via sys.arg[0] ... sy开发者_运维问答s.arg[1] and so forth.


Use argparse or optparse modules to parse your arguments, instead of parsing them yourself. It allows for optional arguments and you can specify a default value.

Here's a quick example using optparse:

import optparse

parser = optparse.OptionParser()

parser.add_option("-d", "--directory", metavar="DIR",
    help="Directory to scan for big files")
parser.add_option("-e", "--email", metavar='EMAIL', 
    help='email to send the list to')

opts, args = parser.parse_args()

print 'scanning', opts.directory

if opts.email is None:
    print 'not sending the email'


Instead of directly assigning arguments to variables via sys.arg, why don't you try using the getopt or argparse modules? It's much easier and more flexible to do so. Here's an example using argparse (from the documentation of Python 2.7):

import argparse

parser = argparse.ArgumentParser(description='Sum or find the max of some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='just an integer')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum command line arguments [default action is to find the maximum]')

args = parser.parse_args() # Simple enough, right?
print args.accumulate(args.integers)

Which you can use (let's call it args.py):

# ./args.py 1 2 3 4
4

# ./args.py 1 2 3 4 --sum
10

I even changed the order of the integer arguments and the --sum and it didn't seem to mind much!

Alternatively, with getopt:

import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hm:v", ["help", "message="])
    except getopt.GetoptError, err:
        print str(err) # will print an error about option not recognized..
        # maybe you should print something informative about correct usage here.
        sys.exit(1)
    # Default option values
    message = None
    verbose = False
    # Process cmd line options
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit(2)
        elif o in ("-m", "--message"):
            message = a
        else:
            assert False, "unhandled option!"
    '''
    Do whatever you wish..
    '''

if __name__ == "__main__":
    main()


For Python-2.4 I believe that optparse is the recommended way to parse command line arguments. It is quite simple to use and it is definitely preferable to parsing options by hand, although it's not as versatile as the newer argparse module which was introduced in Python-2.7.

EDIT:

Here is a (slightly modified) optparse snippet from one of my Python programs:

options = optparse.OptionParser(description = 'Convert Foo to Bar')

options.add_option('-i', '--input', dest = 'input', action = 'store', default = '-')
options.add_option('-j', '--json', dest = 'json', action = 'store_true', default = False)
options.add_option('-m', '--mongodb', dest = 'mongodb', action = 'store', default = None)
options.add_option('-o', '--output', dest = 'output', action = 'store', default = '-')

(options, argv) = options.parse_args(sys.argv)

if options.json:
    print "output: " + options.output
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜