问题
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.
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/24207750/python-2-x-optionnal-subparsers-error-too-few-arguments