The Python Oracle

Having options in argparse with a dash

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC G Dvoks String Quartet No 12 Ame 2

--

Chapters
00:00 Question
00:30 Accepted answer (Score 340)
01:06 Answer 2 (Score 151)
01:56 Answer 3 (Score 26)
02:12 Answer 4 (Score 4)
02:31 Thank you

--

Full question
https://stackoverflow.com/questions/1283...

Accepted answer links:
[indicated in the ]: http://docs.python.org/dev/library/argpa...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #argparse

#avk47



ACCEPTED ANSWER

Score 372


From 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.




ANSWER 2

Score 164


Unfortunately, dash-to-underscore replacement doesn't work for positional arguments (arguments not prefixed by --). For example:

import argparse
import sys

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)
# Namespace(**{'logs-dir': './', 'results-csv': <_io.TextIOWrapper name='mydata.csv' mode='w' encoding='UTF-8'>})

So, you should use the first argument to add_argument() for the attribute name and pass a metavar kwarg to set how it should be displayed in help:

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

print(args)
# Namespace(logs_dir='./', results_csv=<_io.TextIOWrapper name='mydata.csv' mode='w' encoding='UTF-8'>)



ANSWER 3

Score 29


Dashes are converted to underscores:

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



ANSWER 4

Score 3


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.