有选择地指定输出文件但默认使用stdout的最佳方式是什么?
现在我正在尝试:
opts = Trollop::options do
opt :output, "Output File", :default => $stdout
opt :input, "Input File", :default => $stdin
end但当我尝试使用它时,我得到:
$ ./test.rb -o temp.txt
Error: file or url for option '-o' cannot be opened: No such file or directory - temp.txt.
Try --help for help.显然,在运行我的脚本之前,我不想要求输出文件存在。
(另外,我指定输入的方式合适吗?)
发布于 2011-02-07 06:11:54
查看trollop中的代码(特别是parse_io_parameter),我认为目前,trollop (版本1.16.2)假定任何IO类型的参数(如问题中所述)都是用于输入的。
解决方法如下所示。
使用String以trollop格式指定输出文件:
opts = Trollop::options do
opt :input, "Input File", :default => $stdin
opt :output, "Output File", :default => "<stdout>"
end根据解析的参数创建一个输出对象(out):
out = if opts[:output] =~ /^<?stdout>?$/i
$stdout
else
fd = IO.sysopen(opts[:output], "w")
a = IO.new(fd, "w")
end然后你可以像这样使用它:
out.puts("this text gets written to output")https://stackoverflow.com/questions/4912909
复制相似问题