Add an argument that starts with "h"

Viewed 108

With this code, I can't seem to add "--height" as argument because Python is confused with the "-h / --help" default option. I've tried to add add_help=False when creating the object but I still get the error main.py: error: the following arguments are required: height

import argparse

parser = argparse.ArgumentParser(description='my description')
parser.add_argument('height', type=int, nargs=1)

args = parser.parse_args()
1 Answers

You created a positional argument. The way argparse works is that when you define an argument without any leading - or -- it will consider it positional, so you have to call the script like python yourscript.py the_height.

If you want to call it like python myscript.py --height 222 then you must do

parser.add_argument("--height", action="store")
args_namespace = parser.parse_args()
print(args_namespace.height)
Related