1
python test.py --arg -foo -bar
test.py: error: argument --arg: expected at least one argument

python test.py --arg -8
['-8']

How do I allow -non_number to work with argparse?

Is there a way to disable short arguments?

Hec
  • 824
  • 1
  • 5
  • 24
  • This is the problem of handling an argument that looks like a flag: https://stackoverflow.com/questions/48322986/python-argparse-passing-argument-to-argument; https://stackoverflow.com/questions/16174992/cant-get-argparse-to-read-quoted-string-with-dashes-in-it – hpaulj Jan 24 '18 at 21:35

2 Answers2

3

Call it like this:

python test.py --arg='-foo'

To allow specifying multiple:

parser.add_argument('--arg', action='append')
# call like python test.py --arg=-foo --arg=-bar
wim
  • 338,267
  • 99
  • 616
  • 750
1

I think you're looking for the nargs parameter to argparser.

parser.add_argument('--arg', nargs='?')

At the moment, --arg is interpreting the value '-8' as the input, whereas it thinks '-f' (with parameters 'oo') is a new argument.

Alternatively, you could use action='store_true', which will represent the presence or absence of the argument with a boolean.

parser.add_argument('--arg', action='store_true')

https://docs.python.org/3/library/argparse.html#nargs

the_storyteller
  • 2,335
  • 1
  • 26
  • 37