Has anyone worked out how to get boost program options to parse case insensitive argument lists
In the boost documentation, it appears that it is supported. See http://www.boost.org/doc/libs/1_53_0/boost/program_options/cmdline.hpp
Namely, setting the style_t enum flag such as long_case_insensitive. However, I'm not sure how to do it. Eg how would you get the following code snippet to accept --Help or --help or --HELP
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("compression", po::value<double>(), "set compression level")
;
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 0;
}
You can modify the style when you call store. I believe this should work for you:
namespace po_style = boost::program_options::command_line_style;
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc)
.style(po_style::unix_style|po_style::case_insensitive).run(), vm);
po::notify(vm);
Related
This is my minimal example, basically copied from boost web site:
#include <boost/program_options.hpp>
#include <iostream>
namespace po = boost::program_options;
int main(int argc, char **argv) {
po::options_description desc("Test options");
desc.add_options()
("help", "Print help")
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
}
}
When I run:
./main --help
it prints help, as expected. When I run:
./main --foo
it throws unknown_option error, as expected. But when I run:
./main foobar
it ignores the argument and no error is raised. I specify no positional arguments, so I expect boost to raise error here as well.
Why does boost behave this way (I expect that there is some logical reason that I don't see yet)?
What can I do to force boost to strictly check the options provided and raise error on anything else?
Proof of code:
boost::program_options::options_description options;
Parser::Parser(): options("Allowed options")
{
options.add_options()
("help,h", "produce help message")
("type,t", po::value<std::string>()->required()->implicit_value(""), "Type")
}
This line is ok:
("type,t", po::value<std::string>()->required()->implicit_value(""), "Type")
How can I add this line to work correctly?:
("file,f", po::value< std::vector<std::string> >()->required()->multitoken()->implicit_value(std::vector<std::string>(0,"")), "File(s)")
Here is vector of string-s.
You just need to help the options-description to know how to present the default value to the end user.
That is, usually implicit_value would use lexical_cast<> to get the textual representation, but that (obviously) doesn't work for vector<string>. So, supply your own textual representation:
("file,f", po::value<strings>()->required()
->implicit_value(strings { "santa", "claus" }, "santa,claus"), "File(s)");
Full Demo
Live On Coliru
#include <iostream>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main(int argc, char** argv) {
po::options_description options/*("Allowed options")*/;
using strings = std::vector<std::string>;
options.add_options()
("help,h", "produce help message")
("file,f", po::value<strings>()->required()->implicit_value(strings { "santa", "claus" }, "santa,claus"), "File(s)");
std::cout << options << "\n";
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, options, po::command_line_style::default_style), vm);
po::notify(vm);
auto types = vm["file"].as<strings>();
for (auto t : types)
std::cout << "Got: " << t << "\n";
}
Prints:
-h [ --help ] produce help message
-f [ --file ] [=arg(=santa,claus)] File(s)
Got: santa
Got: claus
Could you please help me with boost::program_options?
I want the parser to ignore unknown options that are saved in config file.
I know that allow_unregistered() can be used for cmd line options, how do I proceed with text files?
Here is stripped code:
namespace po = boost::program_options;
try {
string config_file;
string gps_source;
int op_baud;
po::options_description generic("Generic options");
generic.add_options()
("ssdvpacksize", po::value<int>(),
"ssdv packets size in bytes")
("ssdvdir", po::value<string>()->default_value("/ARY1/ssdv"),
"ssdv image dir")
//unused
//I have to specify these even if they're unused
("ssdvproc_dir", po::value<string>(), "")
;
po::options_description file_options;
file_options.add(generic);
po::options_description cli_options("command line interface options");
cli_options.add(generic);
cli_options.add_options()
("config", po::value<string>(&config_file)->default_value("/boot/ary-1.cfg"), "name of a file of a configuration.");
po::variables_map vm;
store( po::command_line_parser(ac, av).options(cli_options).allow_unregistered().run(), vm );
//store( po::basic_command_line_parser<char>(ac, av).options(cli_options).allow_unregistered().run(), vm );
notify(vm);
ifstream ifs(config_file.c_str());
if (!ifs)
{
cout << "Can not open config file: " << config_file << "\n";
}
else
{
// probably smth. to do here ?
//store(parse_config_file(ifs, file_options).allow_unregistered(), vm); // does not work
store(parse_config_file(ifs, file_options), vm);
notify(vm);
}
// ...
// rest of program
}
OK, the solution is embarrassingly easy.
Line 44 should be:
store(parse_config_file(ifs, file_options, true/*allow unregistered*/), vm);
I have a cfg file as the following:
parameter1="hello"
parameter2=22
parameter3=12
Using boost_program to read all the parameters works fine with this code:
po::options_description options("Options");
options.add_options()
("help,h", "produce help message")
("parameter1", po::value<string>(¶meter1)->default_value("bye"),
"parameter1")
("parameter2", po::value<int>(¶meter2)->default_value(2),
"parameter2")
("parameter3", po::value<int>(¶meter3)->default_value(4),
"parameter3");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, options), vm);
notify(vm);
try
{
po::store(po::parse_config_file< char >(filePath, options), vm);
}
catch (const std::exception& e)
{
std::cerr << "Error parsing file: " << filePath << ": " << e.what() << std::endl;
}
...
But when I try to do a generic method where i just want to read one parameter given from a call, I have an error parsing.
I want to read the second parameter for instance, so I write this:
const char parameter_string = "parameter2";
int default = 30;
int parameter;
getparameter(parameter_string,parameter,default);
and goes to the method getsparameter where this is what I have this time:
...
po::options_description options("Options");
options.add_options()
("help,h", "produce help message")
(parameter_string, po::value<int>(¶meter)->default_value(default),
"reading parameter");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, options), vm);
notify(vm);
but the error is:
Error parsing file: file.cfg: unknown option parameter1
So my question is if it is posible to read only one parameter from a file or it is necessary to parse all the parameters with boost_program in options.add_option including as many lines as parameters I write in the config file and then take the value from the parameter I want.
Use allow_unregistered function :
Specifies that unregistered options are allowed and should be passed
though. For each command like token that looks like an option but does
not contain a recognized name, an instance of basic_option will
be added to result, with 'unrecognized' field set to 'true'. It's
possible to collect all unrecognized options with the
'collect_unrecognized' funciton.
As I an using "parse_config_file" I see in the documentation that "allow_unregistered" is set to false by default.
template<typename charT>
BOOST_PROGRAM_OPTIONS_DECL basic_parsed_options< charT >
parse_config_file(std::basic_istream< charT > &,
const options_description &,
bool allow_unregistered = false);
So i modified my line like this:
Old code:
po::store(po::parse_config_file< char >(filePath, options), vm);
New code:
po::store(po::parse_config_file< char >(filePath, options, true), vm);
And as I said, It works. Thank you for your answer.
I am writing the following code on boost's program_options (version 1.42). This seems straight-forward and taken pretty much as is from the tutorial. However, I get a "multiple_occurrences" error. Further investigation discovers that it's (probably) the "filename" parameter that raises it.
The parameters I am giving are:
3 1 test.txt 100
I have no insight to it whatsoever.. any help will be appreciated.
po::options_description common("Common options");
common.add_options()
("help", "produce help message")
("motif_size", po::value<int>(&motif_size), "Size of motif (subgraph)")
("prob", po::value<double>(&prob), "Probably to continue examining an edge")
("filename", po::value<string>(&input_filename), "Filename of the input graph")
("repeats", po::value<int>(&n_estimates), "Number of estimates")
;
po::options_description all;
all.add(common);
po::positional_options_description p;
p.add("motif_size", 0).add("prob", 1).add("filename", 2).add("repeats", 3);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(all).positional(p).run(), vm);
po::notify(vm);
EDIT:
the second parameter to po::positional_options_description::add is the max count, not the position. The position is implied in the order you specify the positional options. So
p.add("motif_size", 0).add("prob", 1).add("filename", 2).add("repeats", 3);
should be
p.add("motif_size", 1).add("prob", 1).add("filename", 1).add("repeats", 1);
Here's a compilable snippet
include <boost/program_options.hpp>
#include <iostream>
#include <string>
int
main(unsigned argc, char** argv)
{
namespace po = boost::program_options;
po::options_description common("Common options");
common.add_options()
("help", "produce help message")
("motif_size", po::value<int>(), "Size of motif (subgraph)")
("prob", po::value<double>(), "Probably to continue examining an edge")
("filename", po::value<std::string>(), "Filename of the input graph")
("repeats", po::value<int>(), "Number of estimates")
;
po::options_description all;
all.add(common);
po::positional_options_description p;
p.add("motif_size", 1).add("prob", 1).add("filename", 1).add("repeats", 1);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).
options(all).positional(p).run(), vm);
po::notify(vm);
} catch ( const boost::program_options::error& e ) {
std::cerr << e.what() << std::endl;
}
return 0;
}
and sample invocation.
macmini:~ samm$ g++ parse.cc -lboost_program_options
macmini:~ samm$ ./a.out 3 1 test.txt 100
macmini:~ samm$
My original answer is below.
What version of program_options? I had the same problem using boost 1.39, to solve it I ended up using boost 1.42.
Here's a link to the ticket describing the problem, and a patch to apply if you don't want to or can't upgrade your copy of boost. To use the new functionality, do something like this
try {
// argument parsing goes here
} catch ( const boost::program_options::multiple_occurrences& e ) {
std::cerr << e.what() << " from option: " << e.get_option_name() << std::endl;
}