百科.dev
全部条目AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
A

argparse

> 数据库
开源

现代 C++ 的参数解析器

3.5K stars0 点赞0 次浏览
访问官网GitHub

工具介绍

现代 C++ 的参数解析器

## Highlights * Single header file * Requires C++17 * MIT License ## Table of Contents * [Quick Start](#quick-start) * [Positional Arguments](#positional-arguments) * [Optional Arguments](#optional-arguments) * [Requiring optional arguments](#requiring-optional-arguments) * [Accessing optional arguments without default values](#accessing-optional-arguments-without-default-values) * [Deciding if the value was given by the user](#deciding-if-the-value-was-given-by-the-user) * [Joining values of repeated optional arguments](#joining-values-of-repeated-optional-arguments) * [Repeating an argument to increase a value](#repeating-an-argument-to-increase-a-value) * [Mutually Exclusive Group](#mutually-exclusive-group) * [Storing values into variables](#store-into) * [Negative Numbers](#negative-numbers) * [Combining Positional and Optional Arguments](#combining-positional-and-optional-arguments) * [Printing Help](#printing-help) * [Adding a description and an epilog to help](#adding-a-description-and-an-epilog-to-help) * [List of Arguments](#list-of-arguments) * [Compound Arguments](#compound-arguments) * [Converting to Numeric Types](#converting-to-numeric-types) * [Default Arguments](#default-arguments) * [Gathering Remaining Arguments](#gathering-remaining-arguments) * [Parent Parsers](#parent-parsers) * [Subcommands](#subcommands) * [Getting Argument and Subparser Instances](#getting-argument-and-subparser-instances) * [Parse Known Args](#parse-known-args) * [Hidden argument and alias](#hidden-argument-alias) * [ArgumentParser in bool Context](#argumentparser-in-bool-context) * [Custom Prefix Characters](#custom-prefix-characters) * [Custom Assignment Characters](#custom-assignment-characters) * [Further Examples](#further-examples) * [Construct a JSON object from a filename argument](#construct-a-json-object-from-a-filename-argument) * [Positional Arguments with Compound Toggle Arguments](#positional-arguments-with-compound-toggle-arguments) * [Restricting the set of values for an argument](#restricting-the-set-of-values-for-an-argument) * [Using `option=value` syntax](#using-optionvalue-syntax) * [Advanced usage formatting](#advanced-usage-formatting) * [Developer Notes](#developer-notes) * [Copying and Moving](#copying-and-moving) * [CMake Integration](#cmake-integration) * [Building, Installing, and Testing](#building-installing-and-testing) * [Supported Toolchains](#supported-toolchains) * [Contributing](#contributing) * [License](#license) ## Quick Start Simply include argparse.hpp and you're good to go. ```cpp #include ``` To start parsing command-line arguments, create an ```ArgumentParser```. ```cpp argparse::ArgumentParser program("program_name"); ``` **NOTE:** There is an optional second argument to the `ArgumentParser` which is the program version. Example: `argparse::ArgumentParser program("libfoo", "1.9.0");` **NOTE:** There are optional third and fourth arguments to the `ArgumentParser` which control default arguments. Example: `argparse::ArgumentParser program("libfoo", "1.9.0", default_arguments::help, false);` See [Default Arguments](#default-arguments), below. To add a new argument, simply call ```.add_argument(...)```. You can provide a variadic list of argument names that you want to group together, e.g., ```-v``` and ```--verbose``` ```cpp program.add_argument("foo"); program.add_argument("-v", "--verbose"); // parameter packing ``` Argparse supports a variety of argument types including positional, optional, and compound arguments. Below you can see how to configure each of these types: ### Positional Arguments Here's an example of a ***positional argument***: ```cpp #include int main(int argc, char *argv[]) { argparse::ArgumentParser program("program_name"); program.add_argument("square") .help("display the square of a given integer") .scan<'i', int>(); try { program.parse_args(argc, argv); } catch (const std::exception& err) { std::cerr << err.what() << std::endl; std::cerr << program; return 1; } auto input = program.get("square"); std::cout << (input * input) << std::endl; return 0; } ``` And running the code: ```console foo@bar:/home/dev/$ ./main 15 225 ``` Here's what's happening: * The ```add_argument()``` method is used to specify which command-line options the program is willing to accept. In this case, I’ve named it square so that it’s in line with its function. * Command-line arguments are strings. To square the argument and print the result, we need to convert this argument to a number. In order to do this, we use the ```.scan``` method to convert user input into an integer. * We can get the value stored by the parser for a given argument using ```parser.get(key)``` method. ### Optional Arguments Now, let's look at ***optional arguments***. Optional arguments start with ```-``` or ```--```, e.g., ```--verbose``` or ```-a```. Optional arguments can be placed anywhere in the input sequence. ```cpp argparse::ArgumentParser program("test"); program.add_argument("--verbose") .help("increase output verbosity") .default_value(false) .implicit_value(true); try { program.parse_args(argc, argv); } catch (const std::exception& err) { std::cerr << err.what() << std::endl; std::cerr << program; std::exit(1); } if (program["--verbose"] == true) { std::cout << "Verbosity enabled" << std::endl; } ``` ```console foo@bar:/home/dev/$ ./main --verbose Verbosity enabled ``` Here's what's happening: * The program is written so as to display something when --verbose is specified and display nothing when not. * Since the argument is actually optional, no error is thrown when running the program without ```--verbose```. Note that by using ```.default_value(false)```, if the optional argument isn’t used, it's value is automatically set to false. * By using ```.implicit_value(true)```, the user specifies that this option is more of a flag than something that requires a value. When the user provides the --verbose option, it's value is set to true. #### Flag When defining flag arguments, you can use the shorthand `flag()` which is the same as `default_value(false).implicit_value(true)`. ```cpp argparse::ArgumentParser program("test"); program.add_argument("--verbose") .help("increase output verbosity") .flag(); try { program.parse_args(argc, argv); } catch (const std::exception& err) { std::cerr << err.what() << std::endl; std::cerr << program; std::exit(1); } if (program["--verbose"] == true) { std::cout << "Verbosity enabled" << std::endl; } ``` #### Requiring optional arguments There are scenarios where you would like to make an optional argument ***required***. As discussed above, optional arguments either begin with `-` or `--`. You can make these types of arguments required like so: ```cpp program.add_argument("-o", "--output") .required() .help("specify the output file."); ``` If the user does not provide a value for this parameter, an exception is thrown. Alternatively, you could provide a default value like so: ```cpp program.add_argument("-o", "--output") .default_value(std::string("-")) .required() .help("specify the output file."); ``` #### Accessing optional arguments without default values If you require an optional argument to be present but have no good default value for it, you can combine testing and accessing the argument as following: ```cpp if (auto fn = program.present("-o")) { do_something_with(*fn); } ``` Similar to `get`, the `present` method also accepts a template argument. But rather than returning `T`, `parser.present(key)` returns `std::optional`, so that when the user does not provide a value to this parameter, the return value compares equal to `std::nullopt`. #### Deciding if the value was given by the user If you want to know whether the user supplied a value for an argument that has a ```.default_value```, check whether the argument ```.is_used()```. ```cpp program.add_argument("--color") .default_value(std::string{"orange"}) // might otherwise be type const char* leading to an error when trying program.get .help("specify the cat's fur color"); try { program.parse_args(argc, argv); // Example: ./main --color orange } catch (const std::exception& err) { std::cerr << err.what() << std::endl; std::cerr << program; std::exit(1); } auto color = program.get("--color"); // "orange" auto explicit_color = program.is_used("--color"); // true, user provided orange ``` #### Joining values of repeated optional arguments You may want to allow an optional argument to be repeated and gather all values in one place. ```cpp program.add_argument("--color") .default_value>({ "orange" }) .append() .help("specify the cat's fur color"); try { program.parse_args(argc, argv); // Example: ./main --color red --color green --color blue } catch (const std::exception& err) { std::cerr << err.what() << std::endl; std::cerr << program; std::exit(1); } auto colors = program.get>("--color"); // {"red", "green", "blue"} ``` Notice that ```.default_value``` is given an explicit template parameter to match the type you want to ```.get```. #### Repeating an argument to increase a value A common pattern is to repeat an argument to indicate a greater value. ```cpp int verbosity = 0; program.add_argument("-V", "--verbose") .action([&](const auto &) { ++verbosity; }) .append() .default_value(false) .implicit_value(true) .nargs(0); program.parse_args(argc, argv); // Example: ./main -VVVV std::cout << "verbose level: " << verbosity << std::endl; // verbose level: 4 ``` #### Mutually Exclusive Group Create a mutually exclusive group using `program.add_mutually_exclusive_group(required = false)`. `argparse`` will make sure that only one of the arguments in the mutually exclusive group was present on the command line: ```cpp auto &group = program.add_mutually_exclusive_group(); group.add_argument("--first"); group.add_argument("--second"); ``` with the following usage will yield an error: ```console foo@bar:/home/dev/$ ./main --first 1 --second 2 Argument '--second VAR' not allowed with '--first VAR' ``` The `add_mutually_exclusive_group()` function also accepts a `required` argument, to indicate that at least one of the mutually exclusive arguments is required: ```cpp auto &group = program.add_mutually_exclusive_group(true); group.add_argument("--first"); group.add_argument("--second"); ``` with the following usage will yield an error: ```console foo@bar:/home/dev/$ ./main One of the arguments '--first VAR' or '--second VAR' is required ``` ### Storing values into variables It is possible to bind arguments to a variable storing their value, as an alternative to explicitly calling ``program.get(arg_name)`` or ``program[arg_name]`` This is currently implementeted for variables of type ``bool`` (this also implicitly calls ``flag()``), ``int``, ``double``, ``std::string``, ``std::vector`` and ``std::vector``. If the argument is not specified in the command line, the default value (if set) is set into the variable. ``` … ``` ### Negative Numbers Optional arguments start with ```-```. Can ```argparse``` handle negative numbers? The answer is yes! ```cpp argparse::ArgumentParser program; program.add_argument("integer") .help("Input number") .scan<'i', int>(); program

Issues· 87 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C++argument-parsercpp17cross-platformheader-only

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类数据库
定价开源

> 相关工具

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库