I'm writing a script and I want to require a --host
switch with value, but if the --host
switch isn't specified, I want the option parsing to fail.
I can't seem to figure out how to do that. The docs seem to only specify how to make the argument value mandatory, not the switch itself.
I turned this into a gem you can download and install from rubygems.org:
And you can checkout the updated project source code on github:
http://github.com/PicklePumpers/pickled_optparse
-- Older post info --
This was really, really bugging me so I fixed it and kept the usage super DRY.
To make a switch required just add a :required symbol anywhere in the array of options like so:
Then at the end of your OptionParser block add one of these to print out the missing switches and the usage instructions:
And finally to make it all work you need to add the following "optparse_required_switches.rb" file to your project somewhere and require it when you do your command line parsing.
I wrote up a little article with an example on my blog: http://picklepumpers.com/wordpress/?p=949
And here's the modified OptionParser file with an example of its usage:
required_switches_example.rb
optparse_required_switches.rb
The answer from unknown (google) is good, but contains a minor error.
should be
Otherwise,
optparse.parse!
will trigger the standard error output forOptionParser::InvalidOption
, not the custom message.The idea is to define an
OptionParser
, thenparse!
it, andputs
it if some fields are missing. Settingfilename
to empty string by default is probably not the best way to go, but you got the idea.If
-i filename
is missing, it displays:I came up with a clear and concise solution that sums up your contributions. It raises an
OptionParser::MissingArgument
exception with the missing arguments as a message. This exception is catched in therescue
block along with the rest of exceptions coming fromOptionParser
.Running this example:
An approach using optparse that provides friendly output on missing switches:
Running without the
-t
or-f
switches shows the following output:Running the parse method in a begin/rescue clause allows friendly formatting upon other failures such as missing arguments or invalid switch values, for instance, try passing a string for the
-n
switch.If host is required, then surely it isn't an option, it's an argument.
With that in mind, here's a way to solve your problem. You can interrogate the
ARGV
array to see if a host has been specified, and, if it hasn't been, then callabort("You must specify a host!")
, or similar, to make your program quit with an error status.