0

Using argparse, is there a way to pass an argument that starts with hyphen, like below?

./py_custom_script -d

I'm adding a change to old script that takes an argument, where with and without hyphen the logic is different. Inspired by this post, I thought of only using positional arg and apply conditional logic internally, but looks like argparse already interprets the one starts with hyphen as an optional arg.

Note that maintaining backward compatibility is a must for this. Both Py 2.7 and 3.x.

IsaacS
  • 3,551
  • 6
  • 39
  • 61
  • The convention is indeed for arguments which start with dashes to be options. If you have a file name argument, pass it as `./-d`. If you just want to pass it through somehow, and you are really sure you know what you are doing, maybe don't use `argparse` at all; or, more realistically, implement the option `-d` so that it prepends the string `-d` to the argument array internally. – tripleee Feb 15 '18 at 01:33
  • There has been active debate as to what do with arguments that look like option flags. The default action for argparse is to treat them as flags, not a arguments. https://docs.python.org/3.6/library/argparse.html#arguments-containing – hpaulj Feb 15 '18 at 02:41

0 Answers0