PChao
PChao

Reputation: 439

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?

Upvotes: 0

Views: 4951

Answers (2)

Patrick Beeson
Patrick Beeson

Reputation: 1695

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',
)

Upvotes: 3

Adam Hughes
Adam Hughes

Reputation: 16319

"-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.

Upvotes: 2

Related Questions