Check if argparse optional argument is set or not

后端 未结 9 1533
臣服心动
臣服心动 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条回答
  •  Happy的楠姐
    2020-12-13 12:07

    If your argument is positional (ie it doesn't have a "-" or a "--" prefix, just the argument, typically a file name) then you can use the nargs parameter to do this:

    parser = argparse.ArgumentParser(description='Foo is a program that does things')
    parser.add_argument('filename', nargs='?')
    args = parser.parse_args()
    
    if args.filename is not None:
        print('The file name is {}'.format(args.filename))
    else:
        print('Oh well ; No args, no problems')
    

提交回复
热议问题