Python argparse: Make at least one argument required

前端 未结 11 1594
谎友^
谎友^ 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 01:47

    If not the 'or both' part (I have initially missed this) you could use something like this:

    parser = argparse.ArgumentParser(description='Log archiver arguments.')
    parser.add_argument('--process', action='store_const', const='process', dest='mode')
    parser.add_argument('--upload',  action='store_const', const='upload', dest='mode')
    args = parser.parse_args()
    if not args.mode:
        parser.error("One of --process or --upload must be given")
    

    Though, probably it would be a better idea to use subcommands instead.

提交回复
热议问题