我创建了相当简单的ruby脚本,它使用Trollop (2.1.2)解析参数。它可以正常工作,直到我传递以-作为参数的值。示例:
def main
opts = Trollop::options do
opt :id, 'Video Id', :type => String
opt :title, 'Video Title', :type => String
end
if opts[:id].nil?
Trollop::die :id, 'please specify --id'
end当我运行它的时候
ruby my_script.rb --id '-WkM3Blu_O8'它因错误而失败
Error: unknown argument '-W'.
Try --help for help.那我怎么处理这个案子?
发布于 2016-05-27 10:58:07
Trollop的工作是解析命令行选项。如果您有一个定义为'-W‘的选项,它将如何区分该选项和以'-W’开头的论点?
因此,即使有一个Trollop选项可以忽略未知选项并让它们作为参数传递给您的程序,如果您定义了任何选项,那么当字符串以连字符开头,后面跟着定义的选项的字母时,仍然会出现问题。
您可以做的一件事是要求想用连字符开始一个参数的用户在它前面加上一个反斜杠。这将成功地对Trollop隐藏它,但是在使用它之前,您需要删除反斜杠。只要反斜杠永远不是id字符串中的合法字符,这应该是可以的。
顺便说一句,您可能希望添加short选项:
require 'trollop'
opts = Trollop::options do
opts = Trollop::options do
opt :id, 'Video Id', type: String, short: :i
opt :title, 'Video Title', type: String, short: :t
end
end
p opts
p ARGV您可以尝试像这样运行它,然后观察结果:
➜ stack_overflow git:(master) ✗ ./trollop.rb -i 3 '\-i1'
{:id=>"3", :title=>nil, :help=>false, :id_given=>true}
["\\-i1"]https://stackoverflow.com/questions/37480363
复制相似问题