简体   繁体   中英

how to use python argparse optional argument

my python code looks like this

parser.add_argument("-c","--configFile",action ='store_true',\
                    help='I am here one travel')

the idea is when running with -c option, I could have select to use my special config file. However, I issue my command python mypython.py -c myconfig , I am getting unrecognized argument: myconfig . What am I missing?

"-c" will store True or False , so why are you passing a value (myconfig) to it? You would call it as:

python mypython.py -c

If you want -c to take an argument, then it shouldn't have the action store_true.

As Adam mentioned, you'll want to change your parser's "action", as stated in the docs .

But it sounds like you want to indicate whether that special config is active, or not. In which case, using action='store_true' or action='store_false' would be correct. You just won't pass the myconfig argument.

parser = argparse.ArgumentParser(description='So something')
parser.add_argument(
    '-c',
    '--c',
    dest='enable_config',
    action='store_true',
    required=False,
    help='Enable special config settings',
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM