Why does this argparse code behave differently between Python 2 and 3?

前端 未结 1 1566
野趣味
野趣味 2020-12-10 02:09

The following code, using argparse\'s subparsers, fails on Python 3 but runs as expected in Python 2. After comparing the docs, I still can\'t tell why.

#!/u         


        
相关标签:
1条回答
  • 2020-12-10 03:05

    the latest argparse release changed how it tested for required arguments, and subparsers fell through the cracks. They are no longer 'required'. http://bugs.python.org/issue9253#msg186387

    When you get test.py: error: too few arguments, it's objecting that you did not give it a 'subcommand' argument. In 3.3.5 it makes it past that step, and returns args.

    With this change, 3.3.5 should behave the same as earlier versions:

    ap = ArgumentParser()
    sp = ap.add_subparsers(dest='parser')  # dest needed for error message
    sp.required = True   # force 'required' testing
    

    Note - both dest and required need to be set. dest is needed to give this argument a name in the error message.


    This error:

    AttributeError: 'Namespace' object has no attribute 'do'
    

    was produced because the cmd subparser did not run, and did not put its arguments (default or not) into the namespace. You can see that effect by defining another subparser, and looking at the resulting args.

    0 讨论(0)
提交回复
热议问题