Python 2.x optionnal subparsers - Error too few ar

2019-02-19 03:20发布

I have been trying to set up a main parser with two subs parser so that when called alone, the main parser would display a help message.

def help_message():
    print "help message"

import argparse
parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(dest='sp')

parser_a = subparsers.add_parser('a')
parser_a.required = False
#some options...
parser_b = subparsers.add_parser('b')
parser_b.required = False
#some options....

args = parser.parse_args([])

if args.sp is None:
    help_message()
elif args.sp == 'a':
    print "a"
elif args.sp == 'b':
    print "b"

This code works well on Python 3 and I would like it to work aswell on Python 2.x

I am getting this when running 'python myprogram.py'

myprogram.py: error: too few arguments

Here is my question : How can i manage to write 'python myprogram.py' in shell and get the help message instead of the error.

2条回答
Luminary・发光体
2楼-- · 2019-02-19 03:48

I think you are dealing the bug discussed in http://bugs.python.org/issue9253

Your subparsers is a positional argument. That kind of argument is always required, unless nargs='?' (or *). I think that is why you are getting the error message in 2.7.

But in the latest py 3 release, the method of testing for required arguments was changed, and subparsers fell through the cracks. Now they are optional (not-required). There's a suggested patch/fudge to make argparse behave as it did before (require a subparser entry). I expect that eventually py3 argparse will revert to the py2 practice (with a possible option of accepting a required=False parameter).

So instead of testing args.sp is None, you may want to test sys.argv[1:] before calling parse_args. Ipython does this to produce it's own help message.

查看更多
The star\"
3楼-- · 2019-02-19 03:52

For others - I ended up on this page while trying to figure out why I couldn't just call my script with no arguments while using argparse in general.

The tutorial demonstrates that the difference between an optional argument and a required argument is adding "--" to the name:

parser.add_argument("--show")  <--- Optional arg
parser.add_argument("show")    <--- Not optional arg
查看更多
登录 后发表回答