Python argparse: Make at least one argument required

前端 未结 11 1728
谎友^
谎友^ 2020-12-13 01:39

I\'ve been using argparse for a Python program that can -process, -upload or both:

parser = argparse.ArgumentParser(de         


        
11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 02:04

    This achieves the purpose and this will also be relfected in the argparse autogenerated --help output, which is imho what most sane programmers want (also works with optional arguments):

    parser.add_argument(
        'commands',
        nargs='+',                      # require at least 1
        choices=['process', 'upload'],  # restrict the choice
        help='commands to execute'
    )
    

    Official docs on this: https://docs.python.org/3/library/argparse.html#choices

提交回复
热议问题