如何将 getoptlong 与变量选项一起使用?
我有几个继承通用 NagiosCheck 类的 Nagios 脚本。由于每个检查都有稍微不同的 getopts 选项,我认为最好通过 NagiosCheck 类方法生成可用选项。但我被困住了......
这就是我调用该方法的方式:
class CheckFoobar < NagiosCheck
...
end
check = CheckFoobar.new
check.generate_options(
['-H', '--hostname', GetoptLong::REQUIRED_ARGUMENT],
['-P', '--port', GetoptLong::REQUIRED_ARGUMENT],
['-u', '--url', GetoptLong::REQUIRED_ARGUMENT])
方法本身:
class NagiosCheck
...
def generate_options (*args)
options = []
args.each do |arg|
options << arg
end
parser = GetoptLong.new
options.each {|arg| parser.set_options(arg)}
end
end
然后解析器仅存储最后一项:
p parser # => #<GetoptLong:0x00000000e17dc8 @ordering=1, @canonical_names={"-u"=>"-u", "--url"=>"-u"}, @argument_flags={"-u"=>1, "--url"=>1}, @quiet=false, @status=0, @error=nil, @error_message=nil, @rest_singles="", @non_option_arguments=[]>
- 您对我如何让解析器存储所有参数有什么建议吗?
问候,
迈克
……关于 stackoverflow 的第一个问题。如果我做错了什么,请容忍我,并让我知道,以便我能够适应。
I have a couple Nagios scripts which inherit a common NagiosCheck class. Since every check has slightly different getopts options I thought it'd be the best to generate the available options via a NagiosCheck class method. But I'm stuck...
This is how I call the method:
class CheckFoobar < NagiosCheck
...
end
check = CheckFoobar.new
check.generate_options(
['-H', '--hostname', GetoptLong::REQUIRED_ARGUMENT],
['-P', '--port', GetoptLong::REQUIRED_ARGUMENT],
['-u', '--url', GetoptLong::REQUIRED_ARGUMENT])
The method itself:
class NagiosCheck
...
def generate_options (*args)
options = []
args.each do |arg|
options << arg
end
parser = GetoptLong.new
options.each {|arg| parser.set_options(arg)}
end
end
Then parser only stores the last item:
p parser # => #<GetoptLong:0x00000000e17dc8 @ordering=1, @canonical_names={"-u"=>"-u", "--url"=>"-u"}, @argument_flags={"-u"=>1, "--url"=>1}, @quiet=false, @status=0, @error=nil, @error_message=nil, @rest_singles="", @non_option_arguments=[]>
- Do you have any advice for me how to get parser to store all arguments?
Regards,
Mike
... First question here on stackoverflow. Please bear with me if I did something wrong and let me know so that I'm able to adapt.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
generate_options 方法太复杂。 Getoptlong.new 采用数组的数组作为参数。
The generate_options method is too complex. Getoptlong.new takes an array of arrays as argument.