![](/img/trans.png)
[英]Sane way to use boost::program_options with INI and command line?
[英]boost::Program_options A way to tell if the value from command line or ini file?
我想知道Boost :: Program_options中是否有一种方法可以指示选项的值(在我的示例中为“ abc”)来自命令行还是ini文件。 原因是如果该值来自ini文件,我将对其进行修改。 这是我的选项说明:
po::options_description desc{ "Options" };
desc.add_options()
("abc", po::wvalue<std::wstring>()->required(), "Path to abc.txt")
("ini", po::wvalue<std::wstring>(), "INI file path.");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("ini"))
{
wifstream ifs(vm["ini"].as<std::wstring>(););
if (ifs)
{
store(po::parse_config_file(ifs, desc, true), vm);
}
}
如您所见,“ abc”是必填选项,因此可以从命令行,ini文件或两种方法(以命令行值具有更高的优先级)输入。 如上所述,我想知道是否有一种方法可以指示“ abc”值的来源,以便我可以相应地修改该值。 谢谢!
在通知所有解析结果并将其合并到单个变量映射中之后,我不知道一种检测有效选项值来源的优雅方法。
但是,您可以通过初步尝试解析命令行,并在通知之前存储inifile和命令行选项来获得所需的结果。
这也消除了以下问题:如果在命令行中未提供强制选项
--abc
则在解析inifile之前notify()
会抱怨缺少强制性选项--abc
。
一个小技巧是使用allow_unregistered()
忽略boostrap_command_line()
内部的所有其他选项:
#include <boost/program_options.hpp>
#include <boost/iostreams/stream.hpp>
#include <fstream>
#include <iostream>
namespace po = boost::program_options;
po::variables_map boostrap_command_line(int argc, char** argv) {
po::options_description desc{ "Bootstrap Options" };
desc.add_options()
("ini", po::value<std::string>()->default_value(""), "INI file path.");
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).allow_unregistered().run(), vm);
po::notify(vm);
return vm;
}
int main(int argc, char** argv) {
po::options_description desc{ "Options" };
auto boostrap = boostrap_command_line(argc, argv);
desc.add_options()
("abc", po::wvalue<std::wstring>()->required(), "Path to abc.txt")
("ini", po::wvalue<std::wstring>(), "INI file path.");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
if (boostrap.count("ini")) {
// Sidenote: the standard does not allow `std::wifstream` to construct from
// `std::wstring`, see
// http://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream
std::wifstream ifs(boostrap["ini"].as<std::string>());
if (ifs) {
store(po::parse_config_file(ifs, desc, true), vm);
}
}
po::notify(vm);
std::wcout << "abc option: " << vm["abc"].as<std::wstring>() << "\n";
}
测试:
$
./a.out --abc direct
abc option: direct
$
touch test.ini
$./a.out --ini test.ini
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::program_options::required_option> >'
what(): the option '--abc' is required but missing
bash: line 9: 11369 Aborted (core dumped) ./a.out --ini test.ini
$
echo abc=fromini >> test.ini
$./a.out --ini test.ini
abc option: fromini
$
./a.out --ini test.ini --abc cli-overrides
abc option: cli-overrides
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.