What's the best way to optionally specify an output file but use stdout by default?
Right now I'm trying:
opts = Trollop::options do
opt :output, "Output File", :default => $stdout
opt :input, "Input File", :default => $stdin
end
But when I try using it, I get:
$ ./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.
Obviously I don't want to require the output file to exist prior to running my script.
(Also, is the way I'm specifying the input okay?)
Looking at the code in trollop (specifically parse_io_parameter
) I believe that currently, trollop (version 1.16.2) assumes any IO
type argument (as in the question) is assumed to be for input.
The workaround is as follows.
Use a String
to specify the output file in trollop:
opts = Trollop::options do
opt :input, "Input File", :default => $stdin
opt :output, "Output File", :default => "<stdout>"
end
Create an output object (out
) based on the parsed argument:
out = if opts[:output] =~ /^<?stdout>?$/i
$stdout
else
fd = IO.sysopen(opts[:output], "w")
a = IO.new(fd, "w")
end
Then you can use it like this:
out.puts("this text gets written to output")