argparse 更改参数定义 [英] argparse change definition of argument
问题描述
我按如下方式设置了我的参数解析器:
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屋!