Subparsers, set_defaults, and func

840 views
Skip to first unread message

Andrew Todd

unread,
Mar 2, 2012, 1:54:59 PM3/2/12
to argpars...@googlegroups.com
I'm trying to set up a command-line parser for basically three commands. Let's call the application "runner." The three commands are as follows:

runner start
runner stop
runner install 1.2.3

As you can see, the "install" command takes an additional version-number argument.

Here's what I have:

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

    start_parser = subparsers.add_parser('start')
    start_parser.set_defaults(func=start)

    stop_parser = subparsers.add_parser('stop')
    stop_parser.set_defaults(func=stop)

    install_parser = subparsers.add_parser('install')
    install_parser.set_defaults(func=install)
    install_parser.add_argument('version')

    parsed_args = parser.parse_args()
    parsed_args.func(parsed_args)

When I run this with "runner install 1.2.3," the function "install" gets called twice, once passing in the Namespace object, and once passing in the version string. This obviously isn't what I intended. Is there a way to prevent this? Thanks.

Giovanni Luca Ciampaglia

unread,
Mar 6, 2012, 4:49:34 AM3/6/12
to argpars...@googlegroups.com
On 03/02/2012 07:54 PM, Andrew Todd wrote:
>
> When I run this with "runner install 1.2.3," the function "install"
> gets called twice, once passing in the Namespace object, and once
> passing in the version string. This obviously isn't what I intended.
> Is there a way to prevent this? Thanks.

Hi Andrew, could you please share the contents of the install function?

I tried your code in the following way and it works for me, i.e. the
function is called once and prints install 1.2.3

***

import argparse

def stop(args):
print 'stop'

def start(args):
print 'start'

def install(args):
print 'install %s' % args.version

if __name__ == '__main__':


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

start_parser = subparsers.add_parser('start')
start_parser.set_defaults(func=start)

stop_parser = subparsers.add_parser('stop')
stop_parser.set_defaults(func=stop)

install_parser = subparsers.add_parser('install')
install_parser.set_defaults(func=install)
install_parser.add_argument('version')

parsed_args = parser.parse_args()
parsed_args.func(parsed_args)

--
Giovanni Luca Ciampaglia

Ph.D. Candidate
Faculty of Informatics
University of Lugano
Web: http://www.inf.usi.ch/phd/ciampaglia/

Bertastraße 36 ∙ 8003 Zürich ∙ Switzerland

Mobile: +41 79 718 8157

Andrew Todd

unread,
Mar 12, 2012, 2:44:08 PM3/12/12
to argpars...@googlegroups.com
Apologies for not responding sooner. Bizarrely, I was having this problem on Friday, to the point where I was doing class type checks for the Namespace object, but could not reproduce the same behavior on the following Monday. I don't know why, but it is now working as I would like.
Reply all
Reply to author
Forward
0 new messages