argparse更改参数的定义 [英] argparse change definition of argument

查看:589
本文介绍了argparse更改参数的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将参数解析器设置如下:

I set up my argument parser as follows:

parser=argparse.ArgumentParser()
parser.add_argument('--point',help='enter a point (e.g. 2,3,4)')
parser.parse_args('--point=-2,5,6'.split())  #works
parser.parse_args('--point -2,5,6'.split())  #doesn't work :(

有什么办法告诉argparse与正则表达式r"-\d+.*"匹配的字符串不是选项而是选项的参数?

Is there any way to tell argparse that strings which match the regular expression r"-\d+.*" are not options but an argument of an option?

还请注意,我可以做这样的事情:

Also note that I could do something like this:

parser.add_argument('--point',nargs='*')
parser.parse_args('--point -2 5 6'.split())

但这不是我真正想要的工作方式.

but that's not really how I want it to work.

推荐答案

如果您不介意argparse内部结构,则argparse已经做了与我想做的非常相似的事情. ArgumentParser继承的类之一在__init__

If you don't mind messing around with argparse internals, argparse already does something very similar to what I want to do. One of the classes that ArgumentParser inherits from has this line in __init__

import re as _re
...
self._negative_number_matcher = _re.compile(r'^-\d+$|^-\d*\.\d+$')

因此,为了使我的示例生效,我们只需要换出适当的正则表达式...

So to get my example to work, we just need to swap out an appropriate regex...

parser._negative_number_matcher = re.compile(r'^-\d+|^-\d*\.\d+')

通常,我不太喜欢在类的内部使用下划线作为前缀时(因为它依赖于实现并且容易更改),所以我不赞成摆弄它们.但是,在这种情况下,我认为可能还可以,因为:

Usually I'm not very much in favor of messing around with the internals of a class when they're prefixed by an underscore (as it is implementation dependent and liable to change) -- However, in this case, I think it's probably ok because:

  • 如果argparse更改了该变量名,那么它不会受到损害,我们回到"--print -2,3,4"不再起作用的情况.
  • 我想不出一种比正则表达式更好的方法来确定某物是否为数字(我想他们可以尝试将其强制转换为浮点数并捕获异常,但是如果这样做,它们将没有变量.一次又一次被命名为_negative_number_matcher,argparse仍然可以正常工作,除非在这种极端情况下,它不能满足我的要求

这篇关于argparse更改参数的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆