将带有破折号的字符串作为参数传递给 Trollop
Passing string with dash as parameter into Trollop
我创建了非常简单的 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.
那么我该如何处理这种情况?
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"]
我创建了非常简单的 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.
那么我该如何处理这种情况?
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"]