argparse

所属分类:虚拟/增强现实-VR/AR
开发工具:C++
文件大小:126KB
下载次数:0
上传日期:2023-05-05 18:52:28
上 传 者sh-1993
说明:  现代C语言的参数分析器++
(Argument Parser for Modern C++)

文件列表:
.clang-format (3274, 2023-07-11)
.clang-tidy (1046, 2023-07-11)
.travis.yml (844, 2023-07-11)
CMakeLists.txt (3317, 2023-07-11)
CONTRIBUTING.md (611, 2023-07-11)
LICENSE (1098, 2023-07-11)
clang_format.bash (64, 2023-07-11)
conanfile.py (233, 2023-07-11)
include (0, 2023-07-11)
include\argparse (0, 2023-07-11)
include\argparse\argparse.hpp (55482, 2023-07-11)
packaging (0, 2023-07-11)
packaging\pkgconfig.pc.in (186, 2023-07-11)
samples (0, 2023-07-11)
samples\CMakeLists.txt (1413, 2023-07-11)
samples\compound_arguments.cpp (1035, 2023-07-11)
samples\custom_assignment_characters.cpp (668, 2023-07-11)
samples\custom_prefix_characters.cpp (764, 2023-07-11)
samples\description_epilog_metavar.cpp (625, 2023-07-11)
samples\gathering_remaining_arguments.cpp (667, 2023-07-11)
samples\is_used.cpp (924, 2023-07-11)
samples\joining_repeated_optional_arguments.cpp (759, 2023-07-11)
samples\list_of_arguments.cpp (749, 2023-07-11)
samples\negative_numbers.cpp (821, 2023-07-11)
samples\optional_flag_argument.cpp (552, 2023-07-11)
samples\parse_known_args.cpp (738, 2023-07-11)
samples\positional_argument.cpp (758, 2023-07-11)
samples\repeating_argument_to_increase_value.cpp (492, 2023-07-11)
samples\required_optional_argument.cpp (491, 2023-07-11)
samples\subcommands.cpp (2372, 2023-07-11)
test (0, 2023-07-11)
... ...

argparse

license version

## Highlights * Single header file * Requires C++17 * MIT License ## Table of Contents * [Quick Start](https://github.com/p-ranav/argparse/blob/master/#quick-start) * [Positional Arguments](https://github.com/p-ranav/argparse/blob/master/#positional-arguments) * [Optional Arguments](https://github.com/p-ranav/argparse/blob/master/#optional-arguments) * [Requiring optional arguments](https://github.com/p-ranav/argparse/blob/master/#requiring-optional-arguments) * [Accessing optional arguments without default values](https://github.com/p-ranav/argparse/blob/master/#accessing-optional-arguments-without-default-values) * [Deciding if the value was given by the user](https://github.com/p-ranav/argparse/blob/master/#deciding-if-the-value-was-given-by-the-user) * [Joining values of repeated optional arguments](https://github.com/p-ranav/argparse/blob/master/#joining-values-of-repeated-optional-arguments) * [Repeating an argument to increase a value](https://github.com/p-ranav/argparse/blob/master/#repeating-an-argument-to-increase-a-value) * [Negative Numbers](https://github.com/p-ranav/argparse/blob/master/#negative-numbers) * [Combining Positional and Optional Arguments](https://github.com/p-ranav/argparse/blob/master/#combining-positional-and-optional-arguments) * [Printing Help](https://github.com/p-ranav/argparse/blob/master/#printing-help) * [Adding a description and an epilog to help](https://github.com/p-ranav/argparse/blob/master/#adding-a-description-and-an-epilog-to-help) * [List of Arguments](https://github.com/p-ranav/argparse/blob/master/#list-of-arguments) * [Compound Arguments](https://github.com/p-ranav/argparse/blob/master/#compound-arguments) * [Converting to Numeric Types](https://github.com/p-ranav/argparse/blob/master/#converting-to-numeric-types) * [Default Arguments](https://github.com/p-ranav/argparse/blob/master/#default-arguments) * [Gathering Remaining Arguments](https://github.com/p-ranav/argparse/blob/master/#gathering-remaining-arguments) * [Parent Parsers](https://github.com/p-ranav/argparse/blob/master/#parent-parsers) * [Subcommands](https://github.com/p-ranav/argparse/blob/master/#subcommands) * [Parse Known Args](https://github.com/p-ranav/argparse/blob/master/#parse-known-args) * [ArgumentParser in bool Context](https://github.com/p-ranav/argparse/blob/master/#argumentparser-in-bool-context) * [Custom Prefix Characters](https://github.com/p-ranav/argparse/blob/master/#custom-prefix-characters) * [Custom Assignment Characters](https://github.com/p-ranav/argparse/blob/master/#custom-assignment-characters) * [Further Examples](https://github.com/p-ranav/argparse/blob/master/#further-examples) * [Construct a JSON object from a filename argument](https://github.com/p-ranav/argparse/blob/master/#construct-a-json-object-from-a-filename-argument) * [Positional Arguments with Compound Toggle Arguments](https://github.com/p-ranav/argparse/blob/master/#positional-arguments-with-compound-toggle-arguments) * [Restricting the set of values for an argument](https://github.com/p-ranav/argparse/blob/master/#restricting-the-set-of-values-for-an-argument) * [Using `option=value` syntax](https://github.com/p-ranav/argparse/blob/master/#using-optionvalue-syntax) * [CMake Integration](https://github.com/p-ranav/argparse/blob/master/#cmake-integration) * [Building, Installing, and Testing](https://github.com/p-ranav/argparse/blob/master/#building-installing-and-testing) * [Supported Toolchains](https://github.com/p-ranav/argparse/blob/master/#supported-toolchains) * [Contributing](https://github.com/p-ranav/argparse/blob/master/#contributing) * [License](https://github.com/p-ranav/argparse/blob/master/#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](https://github.com/p-ranav/argparse/blob/master/#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::runtime_error& 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::runtime_error& 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. #### 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::runtime_error& 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::runtime_error& 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([&](https://github.com/p-ranav/argparse/blob/master/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 ``` ### 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.add_argument("floats") .help("Vector of floats") .nargs(4) .scan<'g', float>(); try { program.parse_args(argc, argv); } catch (const std::runtime_error& err) { std::cerr << err.what() << std::endl; std::cerr << program; std::exit(1); } // Some code to print arguments ``` ```console foo@bar:/home/dev/$ ./main -5 -1.1 -3.1415 -3.1e2 -4.51329E3 integer : -5 floats : -1.1 -3.1415 -310 -4513.29 ``` As you can see here, ```argparse``` supports negative integers, negative floats and scientific notation. ### Combining Positional and Optional Arguments ```cpp argparse::ArgumentParser program("main"); program.add_argument("square") .help("display the square of a given number") .scan<'i', int>(); program.add_argument("--verbose") .default_value(false) .implicit_value(true); try { program.parse_args(argc, argv); } catch (const std::runtime_error& err) { std::cerr << err.what() << std::endl; std::cerr << program; std::exit(1); } int input = program.get("square"); if (program["--verbose"] == true) { std::cout << "The square of " << input << " is " << (input * input) << std::endl; } else { std::cout << (input * input) << std::endl; } ``` ```console foo@bar:/home/dev/$ ./main 4 16 foo@bar:/home/dev/$ ./main 4 --verbose The square of 4 is 16 foo@bar:/home/dev/$ ./main --verbose 4 The square of 4 is 16 ``` ### Printing Help `std::cout << program` prints a help message, including the program usage and information about the arguments registered with the `ArgumentParser`. For the previous example, here's the default help message: ``` foo@bar:/home/dev/$ ./main --help Usage: main [-h] [--verbose] square Positional arguments: square display the square of a given number Optional arguments: -h, --help shows help message and exits -v, --version prints version information and exits --verbose ``` You may also get the help message in string via `program.help().str()`. #### Adding a description and an epilog to help `ArgumentParser::add_description` will add text before the detailed argument information. `ArgumentParser::add_epilog` will add text after all other help output. ```cpp #include int main(int argc, char *argv[]) { argparse::ArgumentParser program("main"); program.add_argument("thing").help("Thing to use.").metavar("THING"); program.add_argument("--member").help("The alias for the member to pass to.").metavar("ALIAS"); program.add_argument("--verbose").default_value(false).implicit_value(true); program.add_description("Forward a thing to the next member."); program.add_epilog("Possible things include betingalw, chiz, and res."); program.parse_args(argc, argv); std::cout << program << std::endl; } ``` ```console Usage: main [-h] [--member ALIAS] [--verbose] THING Forward a thing to the next member. Positional arguments: THING Thing to use. Optional arguments: -h, --help shows help message and exits -v, --version prints version information and exits --member ALIAS The alias for the member to pass to. --verbose Possible things include betingalw, chiz, and res. ``` ### List of Arguments ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The ```.nargs``` associates a different number of command-line arguments with a single action. When using ```nargs(N)```, N arguments from the command line will be gathered together into a list. ```cpp argparse::ArgumentParser program("main"); program.add_argument("--input_files") .help("The list of input files") .nargs(2); try { program.parse_args(argc, argv); // Example: ./main --input_files config.yml System.xml } catch (const std::runtime_error& err) { std::cerr << err.what() << std::endl; std::cerr << program; std::exit(1); } auto files = program.get>("--input_files"); // {"config.yml", "System.xml"} ``` ```ArgumentParser.get()``` has specializations for ```std::vector``` and ```std::list```. So, the following variant, ```.get```, will also work. ```cpp auto files = program.get>("--input_files"); // {"config.yml", "System.xml"} ``` Using ```.scan```, one can quickly build a list of desired value types from command line arguments. Here's an example: ```cpp argparse::ArgumentParser program("main"); program.add_argument("--query_point") .help("3D query point") .nargs(3) .default_value(std::vector{0.0, 0.0, 0.0}) .scan<'g', double>(); try { program.parse_args(argc, argv); // Example: ./main --query_point 3.5 4.7 9.2 } catch (const std::runtime_error& err) { std::cerr << err.what() << std::endl; std::cerr << program; std::exit(1); } auto query_point = program.get>("--query_point"); // {3.5, 4.7, 9.2} ``` You can also make a variable length list of arguments with the ```.nargs```. Below are some examples. ```cpp program.add_argument("--input_files") .nargs(1, 3); // This accepts 1 to 3 arguments. ``` Some useful patterns are defined like "?", "*", "+" of argparse in Python. ```cpp program.add_argument("--input_files") .nargs(argparse::nargs_pattern::any); // "*" in Python. This accepts any number of arguments including 0. ``` ```cpp program.add_argument("--input_files") .nargs(argparse::nargs_pattern::at_least_one); // "+" in Python. This accepts one or more number of arguments. ``` ```cpp program.add_argument("--input_files") .nargs(argparse::nargs_pattern::optional); // "?" in Python. This accepts an argument optionally. ``` ### Compound Arguments Compound arguments are optional arguments that are combined and provided as a single argument. Example: ```ps -aux``` ```cpp argparse::ArgumentParser program("test"); program.add_argument("-a") .default_value(false) .implicit_value(true); program.add_argument("-b") .default_value(false) .implicit_value(true); program.add_argument("-c") .nargs(2) .default_value(std::vector{0.0f, 0.0f}) .scan<'g', float>(); try { program.parse_args(argc, argv); // Example: ./main -abc 1.95 2.47 } catch (const std::runtime_error& err) { std::cerr << err.what() << std::endl; std::cerr << program; std::exit(1); } auto a = program.get("-a"); // true auto b = program.get("-b"); // true auto c = program.get>("-c"); // {1.95, 2.47} /// Some code that prints parsed arguments ``` ```console foo@bar:/home/dev/$ ./main -ac 3.14 2.718 a = true b = false c = {3.14, 2.718} foo@bar:/home/dev/$ ./main -cb a = false b = true c = {0.0, 0.0} ``` Here's what's happening: * We have three optional arguments ```-a```, ```-b``` and ```-c```. * ```-a``` and ```-b``` are toggle arguments. * ```-c``` requires 2 floating point numbers from the command-line. * argparse can handle compound arguments, e.g., ```-abc``` or ```-bac``` or ```-cab```. This only works with short single-character argument names. - ```-a``` and ```-b``` become true. - argv is further parsed to identify the inputs mapped to ```-c```. - If argparse cannot find any arguments to map to c, then c defaults to {0.0, 0.0} as defined by ```.default_value``` ### Converting to Numeric Types For inputs, users can express a primitive type for the value. The ```.scan``` method attempts to convert the incoming `std::string` to `T` following the `Shape` conversion specifier. An `std::invalid_argument` or `std::range_error` exception is thrown for errors. ```cpp program.add_argument("-x") .scan<'d', int>(); program.add_argument("scale") .scan<'g', double>(); ``` `Shape` specifies what the input "looks like", and the type template argument specifies the return value of the predefined action. Acceptable types are floating point (i.e float, double, long double) and integral (i.e. signed char, short, int, long, long long). The grammar follows `std::from_chars`, but does not exactly duplicate it. For example, hexadecimal numbers may begin with `0x` or `0X` and numbers with a leading zero may be handled as octal values. | Shape | interpretation | | :--------: | ----------------------------------------- | | 'a' or 'A' | hexadecimal floating point | | 'e' or 'E' | scientific notation (floating point) | | 'f' or 'F' | fixed notation (floating point) | | 'g' or 'G' | general form (either fixed or scientific) | | | | | 'd' | decimal | | 'i' | `std::from_chars` grammar with base == 0 | | 'o' | octal (unsigned) | | 'u' | decimal (unsigned) | | 'x' or 'X' | hexadecimal (unsigned) | ### Default Arguments `argparse` provides predefined arguments and actions for `-h`/`--help` and `-v`/`--version`. By default, these actions will **exit** the program after displaying a help or version message, respectively. This ex ... ...

近期下载者

相关文件


收藏者