2011-02-06 30 views
1

默认使用stdout指定输出文件的最佳方式是什么?trollop输出文件默认使用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. 

很显然,我不想要求输出文件之前存在运行我的脚本。

(还有,就是我指定的输入行不行呀?)

回答

0

在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")