命令行配置-program_options

来源:互联网 发布:话费查询软件 编辑:程序博客网 时间:2024/06/16 17:21

每次都在IDE上测试数据,最近被弄得烦了,就决定做很多 命令行工具。

决定使用 program_options 库。

这个库的结构如下:

#include <boost/program_options/options_description.hpp>#include <boost/program_options/positional_options.hpp>#include <boost/program_options/parsers.hpp>#include <boost/program_options/variables_map.hpp>#include <boost/program_options/cmdline.hpp>#include <boost/program_options/errors.hpp>#include <boost/program_options/option.hpp>#include <boost/program_options/value_semantic.hpp>#include <boost/program_options/version.hpp>

主要是   描述器 、 解析器、存储器 三个部分而已。

测试demo:

#include <boost/program_options.hpp>#include <laok.h>namespace po = boost::program_options;JOB_DEFINE(boost_program_options , basic){po::options_description desc("Allowed options");desc.add_options()("help", "produce help message")("file", po::value< string >(), "help to gen {Market}_{Code}.csv file list");po::variables_map vm;po::store(po::parse_command_line(JOB_ARGC, JOB_ARGV, desc), vm);po::notify(vm);if (vm.empty() || vm.count("help")) {cout << desc << "\n";return;}if (!vm.count("file")) {cout << " 'file' was not set.\n";return;}else {PS(vm["file"].as<string>());}}


运行效果如下:

E:\restart\workcpp\boost>boost.exe
=====<boost_program_options_basic>begin
Allowed options:
  --help                produce help message
  --file arg            help to gen {Market}_{Code}.csv file list

=====<boost_program_options_basic>end [State:OK] [Times:0.008s]


E:\restart\workcpp\boost>boost.exe --file helloworld.txt
=====<boost_program_options_basic>begin
[vm["file"].as<string>()]:[helloworld.txt]
=====<boost_program_options_basic>end [State:OK] [Times:0.002s]


OK,大功告成。

然后可以定义一堆参数:


            ("optimization", po::value<int>(&opt)->default_value(10),                  "optimization level")            ("verbose,v", po::value<int>()->implicit_value(1),                  "enable verbosity (optionally specify level)")            ("listen,l", po::value<int>(&portnum)->implicit_value(1001)                  ->default_value(0,"no"),                  "listen on a port.")            ("include-path,I", po::value< vector<string> >(),                  "include path")            ("input-file", po::value< vector<string> >(), "input file")

等等。

好用的 boost库模块,这个模块和 python 的 argparse 库一样好用。

good 

0 0
原创粉丝点击