Check if argparse optional argument is set or not

后端 未结 9 1553
臣服心动
臣服心动 2020-12-13 11:48

I would like to check whether an optional argparse argument has been set by the user or not.

Can I safely check using isset?

Something like this:

<         


        
9条回答
  •  甜味超标
    2020-12-13 12:09

    In order to address @kcpr's comment on the (currently accepted) answer by @Honza Osobne

    Unfortunately it doesn't work then the argument got it's default value defined.

    one can first check if the argument was provided by comparing it with the Namespace object abd providing the default=argparse.SUPPRESS option (see @hpaulj's and @Erasmus Cedernaes answers and this python3 doc) and if it hasn't been provided, then set it to a default value.

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--infile', default=argparse.SUPPRESS)
    args = parser.parse_args()
    if 'infile' in args: 
        # the argument is in the namespace, it's been provided by the user
        # set it to what has been provided
        theinfile = args.infile
        print('argument \'--infile\' was given, set to {}'.format(theinfile))
    else:
        # the argument isn't in the namespace
        # set it to a default value
        theinfile = 'your_default.txt'
        print('argument \'--infile\' was not given, set to default {}'.format(theinfile))
    

    Usage

    $ python3 testargparse_so.py
    argument '--infile' was not given, set to default your_default.txt
    
    $ python3 testargparse_so.py --infile user_file.txt
    argument '--infile' was given, set to user_file.txt
    

提交回复
热议问题