Help me debug this script with argparse and if statements

Peter Otten __peter__ at web.de
Thu Feb 21 05:52:45 EST 2013


Chris Angelico wrote:

> On Thu, Feb 21, 2013 at 9:05 PM, Santosh Kumar <sntshkmr60 at gmail.com>
> wrote:
>> parser.add_argument(
>>     'install',
>>     nargs='?',
>>     help='install myapp'
>>     )
>>
>> parser.add_argument(
>>     'uninstall',
>>     nargs='?',
>>     help='uninstall myapp'
>>     )
>>
>> args = parser.parse_args()
> 
> What you've done is make your program expect arguments, not options.
> Try running your script --help and you'll see how it parses. Whatever
> keyword is given goes into args.install, and if you provide a second
> arg, it'll become args.uninstall.
> 
> To do what you're looking for there, I wouldn't bother with argparse
> at all - I'd just look at sys.argv[1] for the word you're looking for.
> Yes, it'd be a bit strict and simplistic, but by the look of things,
> you don't need sophistication.
> 
> ChrisA

There's a simple way to use argparse

import argparse

def install():
    print "installing"
def uninstall():
    print "uninstalling"
def update():
    print "updating"

actions = dict(install=install, update=update, uninstall=uninstall)

parser = argparse.ArgumentParser()
parser.add_argument("action", choices=actions)
args = parser.parse_args()

actions[args.action]()

that doesn't involve a lot of administrative overhead and allows you to add 
options common to all "actions". Then there's the "right" way involving 
subparsers

import argparse

def install(args):
    print "installing"
def uninstall(args):
    print "uninstalling"
def update(args):
    print "updating"

actions = dict(install=install, update=update, uninstall=uninstall)

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

for name, func in actions.iteritems():
    p = subparsers.add_parser(name)
    p.set_defaults(func=func)
args = parser.parse_args()

args.func(args)

which is still not too bad, although in a realistic application you'd have 
to replace the for loop with individual blocks of code for every subparser.





More information about the Python-list mailing list