2

How to parse the parameter with HYPHEN using python argparse module?

MWE

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-idir','--input-dir')
args = parser.parse_args()

# My attempts
idir = args.idir
idir = args.input-dir
idir = args['input-dir']

print(args)

NOTE: Of course I can use an underscore, input_dir but I am looking for a way to parse the parameter with hyphen, e.g. input-dir

BhishanPoudel
  • 15,974
  • 21
  • 108
  • 169
  • This is caused by normalizing arguments, which loses some information. In argparse `--foo=-bar` works, but `--foo -bar` does not. This is because argparse thinks, that -bar is separate argument. – Sumit Yadav Aug 09 '20 at 17:42
  • `... but I am looking for a way to parse the parameter with hyphen` Why? why does it matter? what difference does it make? Use `args.input_dir` – DeepSpace Aug 09 '20 at 17:44
  • 1
    @DeepSpace I inherited some bash scripts with input parameter names such as `input-dir` and I was translating bash script to python script. – BhishanPoudel Aug 09 '20 at 17:46
  • Does this answer your question? [Having options in argparse with a dash](https://stackoverflow.com/questions/12834785/having-options-in-argparse-with-a-dash) – colidyre Aug 09 '20 at 18:27
  • To use the `args.name` syntax `name` has to be a valid Python variable name. It cannot include a `-`. That's why `argparse` converts your argument to `args.input_dir`. – hpaulj Aug 09 '20 at 18:54

1 Answers1

2

I recommend a debugging print:

import argparse    
parser = argparse.ArgumentParser()
parser.add_argument('-idir','--input-dir')
args = parser.parse_args()
print(args)

this shows the actual attribute names:

1156:~/mypy$ python3 stack63329421.py 
Namespace(input_dir=None)
1157:~/mypy$ python3 stack63329421.py -h
usage: stack63329421.py [-h] [-idir INPUT_DIR]

optional arguments:
  -h, --help            show this help message and exit
  -idir INPUT_DIR, --input-dir INPUT_DIR
1157:~/mypy$ python3 stack63329421.py --input-dir foobar
Namespace(input_dir='foobar')

Now I can add a print like:

print(args.input_dir)                  # works with a valid attribute name
print(getattr(args, 'input_dir'))      # works with anything

and get:

1158:~/mypy$ python3 stack63329421.py --input-dir foobar
Namespace(input_dir='foobar')
foobar
foobar

If you don't like the help, add a metavar:

..., metavar='INPUT-DIR'

1158:~/mypy$ python3 stack63329421.py -h
usage: stack63329421.py [-h] [-idir INPUT-DIR]

optional arguments:
  -h, --help            show this help message and exit
  -idir INPUT-DIR, --input-dir INPUT-DIR
hpaulj
  • 221,503
  • 14
  • 230
  • 353