Having options in argparse with a dash

PythonArgparse

Python Problem Overview


I want to have some options in argparse module such as --pm-export however when I try to use it like args.pm-export I get the error that there is not attribute pm. How can I get around this issue? Is it possible to have - in command line options?

Python Solutions


Solution 1 - Python

As indicated in the argparse docs:

> For optional argument actions, the value of dest is normally inferred from the option strings. ArgumentParser generates the value of dest by taking the first long option string and stripping away the initial -- string. Any internal - characters will be converted to _ characters to make sure the string is a valid attribute name

So you should be using args.pm_export.

Solution 2 - Python

Unfortunately, dash-to-underscore replacement doesn't work for positionalarguments (not prefixed by --) like

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('logs-dir',
                    help='Directory with .log and .log.gz files')
parser.add_argument('results-csv', type=argparse.FileType('w'),
                    default=sys.stdout,
                    help='Output .csv filename')
args = parser.parse_args()
print args

# gives
# Namespace(logs-dir='./', results-csv=<open file 'lool.csv', mode 'w' at 0x9020650>)

So, you should use 1'st argument to add_argument() as attribute name and metavar kwarg to set how it should look in help:

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('logs_dir', metavar='logs-dir',
                    nargs=1,
                    help='Directory with .log and .log.gz files')
parser.add_argument('results_csv', metavar='results-csv',
                    nargs=1,
                    type=argparse.FileType('w'),
                    default=sys.stdout,
                    help='Output .csv filename')
args = parser.parse_args()
print args

# gives
# Namespace(logs_dir=['./'], results_csv=[<open file 'lool.csv', mode 'w' at 0xb71385f8>])

Solution 3 - Python

Dashes are converted to underscores:

import argparse
pa = argparse.ArgumentParser()
pa.add_argument('--foo-bar')
args = pa.parse_args(['--foo-bar', '24'])
print args # Namespace(foo_bar='24')

Solution 4 - Python

getattr(args, 'positional-arg')

This is another OK workaround for positional arguments:

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('a-b')
args = parser.parse_args(['123'])
assert getattr(args, 'a-b') == '123'

Tested on Python 3.8.2.

Solution 5 - Python

Concise and explicit but probably not always acceptable way would be to use vars():

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('a-b')
args = vars(parser.parse_args())

print(args['a-b'])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCemre Meng&#252;View Question on Stackoverflow
Solution 1 - PythonThomas OrozcoView Answer on Stackoverflow
Solution 2 - PythonseriyPSView Answer on Stackoverflow
Solution 3 - PythongeorgView Answer on Stackoverflow
Solution 4 - PythonCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow
Solution 5 - PythonDenis The MenaceView Answer on Stackoverflow