Having options in argparse with a dash Having options in argparse with a dash python python

Having options in argparse with a dash


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.


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>])


Dashes are converted to underscores:

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