argparse — requiring either 2 values or none for an optional argument

后端 未结 4 973
你的背包
你的背包 2021-02-06 01:07

I\'m trying to make an optional argument for a script that can either take no values or 2 values, nothing else. Can you accomplish this using argparse?

# desired         


        
4条回答
  •  时光说笑
    2021-02-06 01:42

    Just handle that case yourself:

    parser.add_argument("-a", "--action", nargs='*', action="store", help="do some action")
    args = parser.parse_args()
    
    if args.action is not None:
        if len(args.action) not in (0, 2):
            parser.error('Specify no or two actions')
    
        # action was specified but either there were two actions or no action
    else:
        # action was not specified
    

    Of course you should update the help text in that case so that the user has a chance to know this before running into the error.

提交回复
热议问题