Single dash for argparse long options

不问归期 提交于 2019-12-05 13:18:43

Single dash long arguments aren't a problem:

In [250]: p=argparse.ArgumentParser()

In [251]: p.add_argument('-longargument')
Out[251]: _StoreAction(option_strings=['-longargument'], dest='longargument', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)

In [252]: p.parse_args(['-long','test'])
Out[252]: Namespace(longargument='test')

In [253]: p.parse_args(['-l','test'])
Out[253]: Namespace(longargument='test')

I'd have to double check the code, but I don't think the distinction between long and short options is that significant. When creating the action, all are added to the option_strings attribute. The long (multicharacter) string is used to set the 'dest', but you can also set that yourself.

The behavior that Duffy cites: longoption means a completely different thing: It means -l -o -n -g -p -t -i is more nuanced. If -l,-o, etc are all defined and don't require arguments it will use interpretation. But it doesn't interfer with regular interpretation of -longoption. But you should be aware of such interpretations, and test things during development.


Here's the code used to set the dest for optionals:

    if dest is None:
        if long_option_strings:
            dest_option_string = long_option_strings[0]
        else:
            dest_option_string = option_strings[0]

just before this it collected the strings with -- into the long_option_string` list. But if there isn't such a string, it uses the first string.

In [270]: p.add_argument('-longargument','-l','--longish')
Out[270]: _StoreAction(option_strings=['-longargument', '-l', '--longish'], dest='longish', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)

Here --longish was used instead of -longargument.

The only other place that looks at option string length is the special handling of the -xyz, which focuses on the single character strings ('-x', '-y', '-z').

Justin

Thanks to @CharlesDuffy for the idea.

Just go through sys.argv beforehand and replace each -long-option with --long-option, but remember to intercept the parser's help message too. Something like this:

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(('-h', '--help'), help='Show this message and quit', action='count')
# add other args

new_argv = []
for arg in sys.argv:
    if arg.startswith('-') and len(arg) > 2:
        arg = '-' + arg
    new_argv.append(arg)
sys.argv = new_argv

args = parser.parse_args()
if args.help:
    help_string = parser.format_help()
    print(help_string.replace('--', '-'))
    parser.exit(0)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!