使用Boost Library程序选项的必需参数和可选参数

Pet*_*Lee 73 c++ boost optional boost-program-options required

我正在使用Boost程序选项库来解析命令行参数.

我有以下要求:

  1. 一旦提供"帮助",所有其他选项都是可选的;
  2. 一旦未提供"帮助",则需要所有其他选项.

我怎么处理这个?这是我的代码处理这个,我发现它非常多余,我认为必须有一个容易做的,对吧?

#include <boost/program_options.hpp>
#include <iostream>
#include <sstream>
namespace po = boost::program_options;

bool process_command_line(int argc, char** argv,
                          std::string& host,
                          std::string& port,
                          std::string& configDir)
{
    int iport;

    try
    {
        po::options_description desc("Program Usage", 1024, 512);
        desc.add_options()
          ("help",     "produce help message")
          ("host,h",   po::value<std::string>(&host),      "set the host server")
          ("port,p",   po::value<int>(&iport),             "set the server port")
          ("config,c", po::value<std::string>(&configDir), "set the config path")
        ;

        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, desc), vm);
        po::notify(vm);

        if (vm.count("help"))
        {
            std::cout << desc << "\n";
            return false;
        }

        // There must be an easy way to handle the relationship between the
        // option "help" and "host"-"port"-"config"
        if (vm.count("host"))
        {
            std::cout << "host:   " << vm["host"].as<std::string>() << "\n";
        }
        else
        {
            std::cout << "\"host\" is required!" << "\n";
            return false;
        }

        if (vm.count("port"))
        {
            std::cout << "port:   " << vm["port"].as<int>() << "\n";
        }
        else
        {
            std::cout << "\"port\" is required!" << "\n";
            return false;
        }

        if (vm.count("config"))
        {
            std::cout << "config: " << vm["config"].as<std::string>() << "\n";
        }
        else
        {
            std::cout << "\"config\" is required!" << "\n";
            return false;
        }
    }
    catch(std::exception& e)
    {
        std::cerr << "Error: " << e.what() << "\n";
        return false;
    }
    catch(...)
    {
        std::cerr << "Unknown error!" << "\n";
        return false;
    }

    std::stringstream ss;
    ss << iport;
    port = ss.str();

    return true;
}

int main(int argc, char** argv)
{
  std::string host;
  std::string port;
  std::string configDir;

  bool result = process_command_line(argc, argv, host, port, configDir);
  if (!result)
      return 1;

  // Do the main routine here
}
Run Code Online (Sandbox Code Playgroud)

rco*_*yer 98

我自己也遇到过这个问题.解决方案的关键是函数po::store填充variables_mapwhile po::notify会引发遇到的任何错误,因此vm可以在发送任何通知之前使用.

因此,根据Tim的说法,根据需要将每个选项设置为必需,但po::notify(vm) 在处理完帮助选项后运行.这样它就会退出而不会抛出任何异常.现在,将选项设置为required,缺少选项将导致required_option抛出异常,并且使用其get_option_name方法可以将错误代码减少到相对简单的catch块.

另外请注意,您的选项变量是通过po::value< -type- >( &var_name )机制直接设置的,因此您无需访问它们vm["opt_name"].as< -type- >().

  • 优秀解决方案 官方文档应该用一个例子说清楚. (5认同)

Pet*_*Lee 38

根据rcollyer和Tim,这是完整的计划,学分归于:

#include <boost/program_options.hpp>
#include <iostream>
#include <sstream>
namespace po = boost::program_options;

bool process_command_line(int argc, char** argv,
                          std::string& host,
                          std::string& port,
                          std::string& configDir)
{
    int iport;

    try
    {
        po::options_description desc("Program Usage", 1024, 512);
        desc.add_options()
          ("help",     "produce help message")
          ("host,h",   po::value<std::string>(&host)->required(),      "set the host server")
          ("port,p",   po::value<int>(&iport)->required(),             "set the server port")
          ("config,c", po::value<std::string>(&configDir)->required(), "set the config path")
        ;

        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, desc), vm);

        if (vm.count("help"))
        {
            std::cout << desc << "\n";
            return false;
        }

        // There must be an easy way to handle the relationship between the
        // option "help" and "host"-"port"-"config"
        // Yes, the magic is putting the po::notify after "help" option check
        po::notify(vm);
    }
    catch(std::exception& e)
    {
        std::cerr << "Error: " << e.what() << "\n";
        return false;
    }
    catch(...)
    {
        std::cerr << "Unknown error!" << "\n";
        return false;
    }

    std::stringstream ss;
    ss << iport;
    port = ss.str();

    return true;
}

int main(int argc, char** argv)
{
  std::string host;
  std::string port;
  std::string configDir;

  bool result = process_command_line(argc, argv, host, port, configDir);
  if (!result)
      return 1;

  // else
  std::cout << "host:\t"   << host      << "\n";
  std::cout << "port:\t"   << port      << "\n";
  std::cout << "config:\t" << configDir << "\n";

  // Do the main routine here
}

/* Sample output:

C:\Documents and Settings\plee\My Documents\Visual Studio 2010\Projects\VCLearning\Debug>boost.exe --help
Program Usage:
  --help                produce help message
  -h [ --host ] arg     set the host server
  -p [ --port ] arg     set the server port
  -c [ --config ] arg   set the config path


C:\Documents and Settings\plee\My Documents\Visual Studio 2010\Projects\VCLearning\Debug>boost.exe
Error: missing required option config

C:\Documents and Settings\plee\My Documents\Visual Studio 2010\Projects\VCLearning\Debug>boost.exe --host localhost
Error: missing required option config

C:\Documents and Settings\plee\My Documents\Visual Studio 2010\Projects\VCLearning\Debug>boost.exe --config .
Error: missing required option host

C:\Documents and Settings\plee\My Documents\Visual Studio 2010\Projects\VCLearning\Debug>boost.exe --config . --help
Program Usage:
  --help                produce help message
  -h [ --host ] arg     set the host server
  -p [ --port ] arg     set the server port
  -c [ --config ] arg   set the config path


C:\Documents and Settings\plee\My Documents\Visual Studio 2010\Projects\VCLearning\Debug>boost.exe --host 127.0.0.1 --port 31528 --config .
host:   127.0.0.1
port:   31528
config: .

C:\Documents and Settings\plee\My Documents\Visual Studio 2010\Projects\VCLearning\Debug>boost.exe -h 127.0.0.1 -p 31528 -c .
host:   127.0.0.1
port:   31528
config: .
*/
Run Code Online (Sandbox Code Playgroud)

  • 你应该捕获`boost :: program_options :: required_option`,这样你就可以直接处理缺少必需的选项,而不是让它被`std :: exception`捕获. (3认同)
  • 你应该只捕获boost :: program_options :: error. (2认同)

Tim*_*ter 12

您可以轻松指定一个选项[ 1 ],例如:

..., value<string>()->required(), ...
Run Code Online (Sandbox Code Playgroud)

但据我所知,没有办法表示program_options库的不同选项之间的关系.

一种可能性是使用不同的选项集多次解析命令行,然后如果您已经检查过"帮助",则可以使用所有根据需要设置的其他三个选项再次解析.不过,我不确定我会认为这比你的改进还要好.

  • 是的,很对,我可以放置`-&gt; required()`,但是用户不能通过--help获得帮助信息(不提供所有其他必需的选项),因为还需要其他选项。 (2认同)