How to append new argument after executing parse_args() for argparse in python?

Viewed 2232

I want to use argeparse module in following way,

from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-b', dest='binKey', type=str)
args   = parser.parse_args()

# I will make use of args.binKey option in this space
print args.binKey
# After that I want to add -d option to the arguments

parser.add_argument('-d', dest='dir', type=str)
args   = parser.parse_args()

With this example, I can only provide -b option as shown below in the help text.

$$ python test.py -h
usage: test.py [-h] [-b BINKEY]

optional arguments:
  -h, --help  show this help message and exit
  -b BINKEY

What I want is I should be able to provide both options while running this code and those options should also by visible in --help option

NOTE: I know that I can provide both options before executing parse_args() once, but that is not the way I want to use my parser.

2 Answers

With the help from @hpaulj's comment, here is the resolution:

  • Turn off help option while creating ArgumentParser object.
  • You can call parse_known_args multiple times in between.
  • Add help option at the end.

Below is a snippet of the code

from argparse import ArgumentParser
parser = ArgumentParser(add_help=False)
parser.add_argument('-b', dest='binKey', type=str)
args   = parser.parse_known_args()[0]

# Here you can make use of args.binKey option in this space
print args.binKey
# You can more options after this as

parser.add_argument('-d', dest='dir', type=str)
parser.add_argument('-h', '--help', action='help', default='==SUPPRESS==', help=('show this help message and exit'))
args   = parser.parse_args()

If all you want is to provide both options while running the code you just need to add

parser.add_argument('-d', dest='dir', type=str)

before you execute parse_args(). If this doesn't solve your problem then you need to more explicitly explain why you need to add the argument afterwards.

Related