Python argparse: Make at least one argument required

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

    If you require a python program to run with at least one parameter, add an argument that doesn't have the option prefix (- or -- by default) and set nargs=+ (Minimum of one argument required). The problem with this method I found is that if you do not specify the argument, argparse will generate a "too few arguments" error and not print out the help menu. If you don't need that functionality, here's how to do it in code:

    import argparse
    
    parser = argparse.ArgumentParser(description='Your program description')
    parser.add_argument('command', nargs="+", help='describe what a command is')
    args = parser.parse_args()
    

    I think that when you add an argument with the option prefixes, nargs governs the entire argument parser and not just the option. (What I mean is, if you have an --option flag with nargs="+", then --option flag expects at least one argument. If you have option with nargs="+", it expects at least one argument overall.)

提交回复
热议问题