c++ program_options实现子命令

参考:https://gist.github.com/randomphrase/10801888
code: https://gitee.com/kacakaca/Test/blob/master/basic_cpp/parseoptions.cpp

  • 使用g++ -std=c++11 parseoptions.cpp -lboost_program_options编译后, 执行:
    capture command: ./a.out capture --device 2 --stream 1920x1080@30
    control command: ./a.out control -z 150 -m 10,30 -b 128

  • 使用options_description的add_options描述参数,例如

    po::options_description desc("Usage");
    desc.add_options()
        ("help,h", "print this message")
        ("[command]", po::value<std::string>(&cmd), "[command] include 'capture', 'control'")
        ("[command_args]", po::value<std::vector<std::string>>(&cmd_args), "args of [command]");
    
    po::options_description command_capture_desc("command capture options");
    command_capture_desc.add_options()
        ("help,h", "")
        ("device,d", po::value<int>(&deviceid)->required(), "specific device number")
        ("stream,s", po::value<std::string>(&stream)->default_value("1920x1080@30"), "specific stream config");
    
    po::options_description command_control_desc("command control options");
    command_control_desc.add_options()
        ("help,h", "capture stream with different zoom, move or brightness camera control value")
        ("zoom,z", po::value<int>(&zoom), "zoom value")
        ("move,m", po::value<std::string>(&move), "move value")
        ("brightness,b", po::value<int>(&brightness), "zoom value");
    
  • 其中用到了positional_opions_description, 所以可以实现不同的命令层次, 其中1表示命令的第一个参数,即上面的命令中的‘capture’或‘control’; -1表示任意位置

    po::positional_options_description pos;
    pos.add("[command]", 1)
       .add("[command_args]", -1);
    
  • 然后用program_options的相关函数,先处理第一个参数:

    po::parsed_options all_options = po::command_line_parser(argc, argv)
                                            .options(desc)
                                            .positional(pos)
                                            .allow_unregistered()
                                            .run();
    po::store(all_options, vm);
    po::notify(vm);
    
  • 然后根据这个参数的不同值进行后续的处理:

    auto opts = po::collect_unrecognized(all_options.options, po::include_positional);
    if (cmd == "capture") {
          
          
        po::store(po::command_line_parser(opts).options(command_capture_desc).run(), vm);
        po::notify(vm);
    
        std::cout << "device number:" << deviceid << std::endl;
        std::cout << "stream config:" << stream << std::endl;
    } else if (cmd == "control") {
          
          
        po::store(po::command_line_parser(opts).options(command_control_desc).run(), vm);
        po::notify(vm);
    
        if (vm.count("zoom") > 0) {
          
          
            std::cout << "zoom:" << zoom << std::endl;
        }
    }
    

猜你喜欢

转载自blog.csdn.net/iamanda/article/details/114372507