Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4027808
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T11:08:34+00:00 2026-05-20T11:08:34+00:00

I am using the argparse package of Python 2.7 to write some option-parsing logic

  • 0

I am using the argparse package of Python 2.7 to write some option-parsing logic for a command-line tool. The tool should accept one of the following arguments:

“ON”: Turn a function on.
“OFF”: Turn a function off.
[No arguments provided]: Echo the current state of the function.

Looking at the argparse documentation led me to believe that I wanted two–possibly three–subcommands to be defined, since these three states are mutually exclusive and represent different conceptual activities. This is my current attempt at the code:

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
parser.set_defaults(func=print_state) # I think this line is wrong.

parser_on = subparsers.add_parser('ON')
parser_on.set_defaults(func=set_state, newstate='ON')

parser_off = subparsers.add_parser('OFF')
parser_off.set_defaults(func=set_state, newstate='OFF')

args = parser.parse_args()

if(args.func == set_state):
    set_state(args.newstate)
elif(args.func == print_state):
    print_state()
else:
    args.func() # Catchall in case I add more functions later

I was under the impression that if I provided 0 arguments, the main parser would set func=print_state, and if I provided 1 argument, the main parser would use the appropriate subcommand’s defaults and call func=set_state. Instead, I get the following error with 0 arguments:

usage: cvsSecure.py [-h] {ON,OFF} ...
cvsSecure.py: error: too few arguments

And if I provide “OFF” or “ON”, print_state gets called instead of set_state. If I comment out the parser.set_defaults line, set_state is called correctly.

I’m a journeyman-level programmer, but a rank beginner to Python. Any suggestions about how I can get this working?

Edit: Another reason I was looking at subcommands was a potential fourth function that I am considering for the future:

“FORCE txtval”: Set the function’s state to txtval.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T11:08:34+00:00Added an answer on May 20, 2026 at 11:08 am

    The defaults of the top-level parser override the defaults on the sub-parsers, so setting the default value of func on the sub-parsers is ignored, but the value of newstate from the sub-parser defaults is correct.

    I don’t think you want to use subcommands. Subcommands are used when the available options and positional arguments change depending on which subcommand is chosen. However, you have no other options or positional arguments.

    The following code seems to do what you require:

    import argparse
    
    def print_state():
        print "Print state"
    
    def set_state(s):
        print "Setting state to " + s
    
    parser = argparse.ArgumentParser()
    parser.add_argument('state', choices = ['ON', 'OFF'], nargs='?')
    
    args = parser.parse_args()
    
    if args.state is None:
        print_state()
    elif args.state in ('ON', 'OFF'):
        set_state(args.state)
    

    Note the optional parameters to parser.add_argument. The “choices” parameter specifies the allowable options, while setting “nargs” to “?” specifies that 1 argument should be consumed if available, otherwise none should be consumed.

    Edit: If you want to add a FORCE command with an argument and have separate help text for the ON and OFF command then you do need to use subcommands. Unfortunately there doesn’t seem to be a way of specifying a default subcommand. However, you can work around the problem by checking for an empty argument list and supplying your own. Here’s some sample code illustrating what I mean:

    import argparse
    import sys
    
    def print_state(ignored):
        print "Print state"
    
    def set_state(s):
        print "Setting state to " + s
    
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()
    on = subparsers.add_parser('ON', help = 'On help here.')
    on.set_defaults(func = set_state, newstate = 'ON')
    off = subparsers.add_parser('OFF', help = 'Off help here.')
    off.set_defaults(func = set_state, newstate = 'OFF')
    prt = subparsers.add_parser('PRINT')
    prt.set_defaults(func = print_state, newstate = 'N/A')
    force = subparsers.add_parser('FORCE' , help = 'Force help here.')
    force.add_argument('newstate', choices = [ 'ON', 'OFF' ])
    force.set_defaults(func = set_state)
    
    if (len(sys.argv) < 2):
        args = parser.parse_args(['PRINT'])
    else:
        args = parser.parse_args(sys.argv[1:])
    
    args.func(args.newstate)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using argparse in Python 2.7 for parsing input options. One of my options
I am writing a command line tool in Python using the Cmd module. I
Using PyObjC , you can use Python to write Cocoa applications for OS X.
Using C# .NET 3.5 and WCF, I'm trying to write out some of the
If I write a python script using only python standard libraries, using Python 2.6
I am using argparse in my python program and I want to call a
Using TortoiseSVN against VisualSVN I delete a source file that I should not have
For my project I would be using the argparse library. My question is, how
Using the argparse module, is it possible to perform multiple actions for a given
When using optparse i want to get the whole string after an option, but

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.