Chris F
Chris F

Reputation: 16673

How do I make command line arguments with a hyphen (-) show up as non-optional in python v2.7?

I have the following python script

parser = argparse.ArgumentParser(description='Process controller.py arguments')
parser.add_argument("-b", help='Build number, e.g., 1234')
args = vars(parser.parse_args())

When I run it I get...

$ python CommandLineParser.py -h
usage: CommandLineParser.py [-h] [-b B]

Process controller.py arguments

optional arguments:
  -h, --help  show this help message and exit
  -b B        Build number, e.g., 1234

How do I make the "-b" show up as a "non-optional" argument (because it's NOT!). As an added bonus, how do I rid of the uppercase "B" after it? Thanks!

Upvotes: 3

Views: 1529

Answers (2)

alecxe
alecxe

Reputation: 473833

You need to set required to True and metavar (it's responsible for B) to '':

parser.add_argument("-b", help='Build number, e.g., 1234', required=True, metavar='')

Actually, you will still see your required argument as optional if run your script in a help mode. This is because of a bug: argparse required arguments displayed under "optional arguments":

The argparse module lists required args as optional in the default help message.

There are also some workarounds suggested, but I like this one more: add your own required arguments group:

required_group = parser.add_argument_group('required arguments')
required_group.add_argument("-b", help='Build number, e.g., 1234', required=True, metavar='')

Then, you will see this on a command-line:

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

Process controller.py arguments

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

required arguments:
  -b          Build number, e.g., 1234

Upvotes: 3

Manoj Pandey
Manoj Pandey

Reputation: 4666

Please use the required keyword when adding it to the argparse: http://docs.python.org/2/library/argparse.html#sub-commands

parser.add_argument("-b", help='Build number, e.g., 1234', required=True)

Upvotes: 0

Related Questions