Python argparse: Make at least one argument required

前端 未结 11 1679
谎友^
谎友^ 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:49

    Use append_const to a list of actions and then check that the list is populated:

    parser.add_argument('-process', dest=actions, const="process", action='append_const')
    parser.add_argument('-upload',  dest=actions, const="upload", action='append_const')
    
    args = parser.parse_args()
    
    if(args.actions == None):
        parser.error('Error: No actions requested')
    

    You can even specify the methods directly within the constants.

    def upload:
        ...
    
    parser.add_argument('-upload',  dest=actions, const=upload, action='append_const')
    args = parser.parse_args()
    
    if(args.actions == None):
        parser.error('Error: No actions requested')
    
    else:
        for action in args.actions:
            action()
    

提交回复
热议问题