您当前的位置:首页 > 电脑百科 > 程序开发 > 语言 > C/C++/C#

简单、小巧、灵活的C++11单头文件的命令行参数解析库args.hxx

时间:2023-05-19 14:37:28  来源:  作者:山城科技峰

概述

命令行参数解析,在写一些命令行的程序时需要用到,args.hxx类似于Python/ target=_blank class=infotextkey>Python的argparse,但在C++中,它具有静态类型检查,并且速度更快(也允许完全嵌套的组逻辑,而Python的argparse没有),支持自定义类型解析,子命令等。使用上,只需要在工程中include “args.hxx” 就可以正常使用,符合C++11规范,兼容性更好。

 

文档和源码

API文档地址: https://taywee.Github.io/args
源码地址: at https://github.com/Taywee/args

范例

以下的所有代码示例都将是完整的代码示例,并带有一些输出。

简单范例

#include <IOStream>
#include <args.hxx>
int main(int argc, char **argv)
{
    args::ArgumentParser parser("This is a test program.", "This goes after the options.");
    args::HelpFlag help(parser, "help", "Display this help menu", {'h', "help"});
    args::CompletionFlag completion(parser, {"complete"});
    try
    {
        parser.ParseCLI(argc, argv);
    }
    catch (const args::Completion& e)
    {
        std::cout << e.what();
        return 0;
    }
    catch (const args::Help&)
    {
        std::cout << parser;
        return 0;
    }
    catch (const args::ParseError& e)
    {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }
    return 0;
}

运行输出:

 % ./test
 % ./test -h
  ./test {OPTIONS} 

    This is a test program. 

  OPTIONS:

      -h, --help         Display this help menu 

    This goes after the options. 
 % 

布尔标志、特殊组类型、不同的匹配器构造

#include <iostream>
#include <args.hxx>
int main(int argc, char **argv)
{
    args::ArgumentParser parser("This is a test program.", "This goes after the options.");
    args::Group group(parser, "This group is all exclusive:", args::Group::Validators::Xor);
    args::Flag foo(group, "foo", "The foo flag", {'f', "foo"});
    args::Flag bar(group, "bar", "The bar flag", {'b'});
    args::Flag baz(group, "baz", "The baz flag", {"baz"});
    try
    {
        parser.ParseCLI(argc, argv);
    }
    catch (args::Help)
    {
        std::cout << parser;
        return 0;
    }
    catch (args::ParseError e)
    {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }
    catch (args::ValidationError e)
    {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }
    if (foo) { std::cout << "foo" << std::endl; }
    if (bar) { std::cout << "bar" << std::endl; }
    if (baz) { std::cout << "baz" << std::endl; }
    return 0;
}

运行输出:

 % ./test   
Group validation failed somewhere!
  ./test {OPTIONS} 

    This is a test program. 

  OPTIONS:

                         This group is all exclusive:
        -f, --foo          The foo flag 
        -b                 The bar flag 
        --baz              The baz flag 

    This goes after the options. 
 % ./test -f
foo
 % ./test --foo
foo
 % ./test --foo -f
foo
 % ./test -b      
bar
 % ./test --baz
baz
 % ./test --baz -f
Group validation failed somewhere!
  ./test {OPTIONS} 

    This is a test program. 
...
 % ./test --baz -fb
Group validation failed somewhere!
  ./test {OPTIONS} 
...
 % 

参数标志、位置参数、列表

#include <iostream>
#include <args.hxx>
int main(int argc, char **argv)
{
    args::ArgumentParser parser("This is a test program.", "This goes after the options.");
    args::HelpFlag help(parser, "help", "Display this help menu", {'h', "help"});
    args::ValueFlag<int> integer(parser, "integer", "The integer flag", {'i'});
    args::ValueFlagList<char> characters(parser, "characters", "The character flag", {'c'});
    args::Positional<std::string> foo(parser, "foo", "The foo position");
    args::PositionalList<double> numbers(parser, "numbers", "The numbers position list");
    try
    {
        parser.ParseCLI(argc, argv);
    }
    catch (args::Help)
    {
        std::cout << parser;
        return 0;
    }
    catch (args::ParseError e)
    {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }
    catch (args::ValidationError e)
    {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }
    if (integer) { std::cout << "i: " << args::get(integer) << std::endl; }
    if (characters) { for (const auto ch: args::get(characters)) { std::cout << "c: " << ch << std::endl; } }
    if (foo) { std::cout << "f: " << args::get(foo) << std::endl; }
    if (numbers) { for (const auto nm: args::get(numbers)) { std::cout << "n: " << nm << std::endl; } }
    return 0;
}

运行输出:

% ./test -h
  ./test {OPTIONS} [foo] [numbers...] 

    This is a test program. 

  OPTIONS:

      -h, --help         Display this help menu 
      -i integer         The integer flag 
      -c characters      The character flag 
      foo                The foo position 
      numbers            The numbers position list 
      "--" can be used to terminate flag options and force all following
      arguments to be treated as positional options 

    This goes after the options. 
 % ./test -i 5
i: 5
 % ./test -i 5.2
Argument 'integer' received invalid value type '5.2'
  ./test {OPTIONS} [foo] [numbers...] 
 % ./test -c 1 -c 2 -c 3
c: 1
c: 2
c: 3
 % 
 % ./test 1 2 3 4 5 6 7 8 9
f: 1
n: 2
n: 3
n: 4
n: 5
n: 6
n: 7
n: 8
n: 9
 % ./test 1 2 3 4 5 6 7 8 9 a
Argument 'numbers' received invalid value type 'a'
  ./test {OPTIONS} [foo] [numbers...] 

    This is a test program. 
...

命令行子命令

#include <iostream>
#include <args.hxx>
int main(int argc, char **argv)
{
    args::ArgumentParser p("git-like parser");
    args::Group commands(p, "commands");
    args::Command add(commands, "add", "add file contents to the index");
    args::Command commit(commands, "commit", "record changes to the repository");
    args::Group arguments(p, "arguments", args::Group::Validators::DontCare, args::Options::Global);
    args::ValueFlag<std::string> gitdir(arguments, "path", "", {"git-dir"});
    args::HelpFlag h(arguments, "help", "help", {'h', "help"});
    args::PositionalList<std::string> pathsList(arguments, "paths", "files to commit");

    try
    {
        p.ParseCLI(argc, argv);
        if (add)
        {
            std::cout << "Add";
        }
        else
        {
            std::cout << "Commit";
        }

        for (auto &&path : pathsList)
        {
            std::cout << ' ' << path;
        }

        std::cout << std::endl;
    }
    catch (args::Help)
    {
        std::cout << p;
    }
    catch (args::Error& e)
    {
        std::cerr << e.what() << std::endl << p;
        return 1;
    }
    return 0;
}

运行输出:

% ./test -h
  ./test COMMAND [paths...] {OPTIONS}

    git-like parser

  OPTIONS:

      commands
        add                               add file contents to the index
        commit                            record changes to the repository
      arguments
        --git-dir=[path]
        -h, --help                        help
        paths...                          files
      "--" can be used to terminate flag options and force all following
      arguments to be treated as positional options

% ./test add 1 2
Add 1 2

重构子命令

#include <iostream>
#include "args.hxx"

args::Group arguments("arguments");
args::ValueFlag<std::string> gitdir(arguments, "path", "", {"git-dir"});
args::HelpFlag h(arguments, "help", "help", {'h', "help"});
args::PositionalList<std::string> pathsList(arguments, "paths", "files to commit");

void CommitCommand(args::Subparser &parser)
{
    args::ValueFlag<std::string> message(parser, "MESSAGE", "commit message", {'m'});
    parser.Parse();

    std::cout << "Commit";

    for (auto &&path : pathsList)
    {
        std::cout << ' ' << path;
    }

    std::cout << std::endl;

    if (message)
    {
        std::cout << "message: " << args::get(message) << std::endl;
    }
}

int main(int argc, const char **argv)
{
    args::ArgumentParser p("git-like parser");
    args::Group commands(p, "commands");
    args::Command add(commands, "add", "add file contents to the index", [&](args::Subparser &parser)
    {
        parser.Parse();
        std::cout << "Add";

        for (auto &&path : pathsList)
        {
            std::cout << ' ' << path;
        }

        std::cout << std::endl;
    });

    args::Command commit(commands, "commit", "record changes to the repository", &CommitCommand);
    args::GlobalOptions globals(p, arguments);

    try
    {
        p.ParseCLI(argc, argv);
    }
    catch (args::Help)
    {
        std::cout << p;
    }
    catch (args::Error& e)
    {
        std::cerr << e.what() << std::endl << p;
        return 1;
    }
    return 0;
}

运行结果:

% ./test -h
  ./test COMMAND [paths...] {OPTIONS}

    git-like parser

  OPTIONS:

      commands
        add                               add file contents to the index
        commit                            record changes to the repository
      arguments
        --git-dir=[path]
        -h, --help                        help
        paths...                          files
      "--" can be used to terminate flag options and force all following
      arguments to be treated as positional options

% ./test add 1 2
Add 1 2

% ./test commit -m "my commit message" 1 2
Commit 1 2
message: my commit message

自定义类型解析器

这里我们使用std::tuple

#include <iostream>
#include <tuple>

std::istream& operator>>(std::istream& is, std::tuple<int, int>& ints)
{
    is >> std::get<0>(ints);
    is.get();
    is >> std::get<1>(ints);
    return is;
}

#include <args.hxx>

struct DoublesReader
{
    void operator()(const std::string &name, const std::string &value, std::tuple<double, double> &destination)
    {
        size_t commapos = 0;
        std::get<0>(destination) = std::stod(value, &commapos);
        std::get<1>(destination) = std::stod(std::string(value, commapos + 1));
    }
};

int main(int argc, char **argv)
{
    args::ArgumentParser parser("This is a test program.");
    args::Positional<std::tuple<int, int>> ints(parser, "INTS", "This takes a pair of integers.");
    args::Positional<std::tuple<double, double>, DoublesReader> doubles(parser, "DOUBLES", "This takes a pair of doubles.");
    try
    {
        parser.ParseCLI(argc, argv);
    }
    catch (args::Help)
    {
        std::cout << parser;
        return 0;
    }
    catch (args::ParseError e)
    {
        std::cerr << e.what() << std::endl;
        std::cerr << parser;
        return 1;
    }
    if (ints)
    {
        std::cout << "ints found: " << std::get<0>(args::get(ints)) << " and " << std::get<1>(args::get(ints)) << std::endl;
    }
    if (doubles)
    {
        std::cout << "doubles found: " << std::get<0>(args::get(doubles)) << " and " << std::get<1>(args::get(doubles)) << std::endl;
    }
    return 0;
}

运行输出:

 % ./test -h
Argument could not be matched: 'h'
  ./test [INTS] [DOUBLES] 

    This is a test program. 

  OPTIONS:

      INTS               This takes a pair of integers. 
      DOUBLES            This takes a pair of doubles. 

 % ./test 5
ints found: 5 and 0
 % ./test 5,8
ints found: 5 and 8
 % ./test 5,8 2.4,8
ints found: 5 and 8
doubles found: 2.4 and 8
 % ./test 5,8 2.4, 
terminate called after throwing an instance of 'std::invalid_argument'
  what():  stod
zsh: abort      ./test 5,8 2.4,
 % ./test 5,8 2.4 
terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::basic_string: __pos (which is 4) > this->size() (which is 3)
zsh: abort      ./test 5,8 2.4
 % ./test 5,8 2.4-7
ints found: 5 and 8
doubles found: 2.4 and 7
 % ./test 5,8 2.4,-7
ints found: 5 and 8
doubles found: 2.4 and -7

更多范例请参考github上的手册:https://github.com/Taywee/args



Tags:C++   点击:()  评论:()
声明:本站部分内容及图片来自互联网,转载是出于传递更多信息之目的,内容观点仅代表作者本人,不构成投资建议。投资者据此操作,风险自担。如有任何标注错误或版权侵犯请与我们联系(Email:2595517585@qq.com),我们将及时更正、删除。
▌相关推荐
前言JSON是很常用的数据格式,在C++中我们可以使用nlohmann json做序列化和反序列化。 nlohmann json是一个跨平台的开源的C++ JSON解析库,只需要在项目中#include "json.hpp"...【详细内容】
2023-05-22  Tags: C++  点击:(1)  评论:(0)  加入收藏
概述命令行参数解析,在写一些命令行的程序时需要用到,args.hxx类似于Python的argparse,但在C++中,它具有静态类型检查,并且速度更快(也允许完全嵌套的组逻辑,而Python的argparse没...【详细内容】
2023-05-19  Tags: C++  点击:(0)  评论:(0)  加入收藏
取代C++!微软正在改用Rust语言重写Win11内核微软已经确定结束对Win10进行功能更新,其更多精力将转移到Win11以及“Win12”上。在日前举办的BlueHat IL 2023 大会上,微软企业和...【详细内容】
2023-04-29  Tags: C++  点击:(34)  评论:(0)  加入收藏
C++自适应函数符和函数适配器是C++标准库中非常重要的概念,它们为C++程序员提供了更加灵活和高效的编程方式。自适应函数符是指一类函数对象,可以根据输入的参数类型自动推导...【详细内容】
2023-04-14  Tags: C++  点击:(30)  评论:(0)  加入收藏
C++11 中新增了一种智能指针类型 unique_ptr,它是一种独占式的智能指针,用于管理动态分配的对象,并确保在其生命周期结束时正确释放资源。在使用 unique_ptr 时,指针指向的资源...【详细内容】
2023-04-08  Tags: C++  点击:(35)  评论:(0)  加入收藏
第一、四个用途用途一:定义一种类型的别名,而不只是简单的宏替换。可以用作同时声明指针型的多个对象。比如:char* pa, pb; // 这多数不符合我们的意图,它只声明了一个指向字符...【详细内容】
2023-04-03  Tags: C++  点击:(33)  评论:(0)  加入收藏
作 者 | 吴强强(去鸿)作者最近尝试写了一些Rust代码,本文主要讲述了对Rust的看法和Rust与C++的一些区别。背景S2在推进团队代码规范时,先后学习了盘古编程规范,CPP core guide...【详细内容】
2023-03-31  Tags: C++  点击:(28)  评论:(0)  加入收藏
C++、C和汇编语言是计算机编程中常见的三种编程语言。它们之间有很多相似之处,也有很多不同之处。首先,C++和C都是高级语言,而汇编语言是低级语言。高级语言是一种人类易于理解...【详细内容】
2023-03-29  Tags: C++  点击:(28)  评论:(0)  加入收藏
【CSDN 编者按】开发者 Nikita Lapkov :从 C++ 切换到 Rust 后,日常工作体验得到了极大地提升。原文链接:https://laplab.me/posts/switching-from-cpp-to-rust/作者 | Nikita...【详细内容】
2023-03-28  Tags: C++  点击:(39)  评论:(0)  加入收藏
双减后,数竞赛道受限,信竞赛道涌入不少青少年身影。然而,想要参加信息学奥赛,就得学会使用程序语言,目前国内信息学奥赛的指定语言是C++,若要在小初阶段冲刺竞赛高分,不少人首选编...【详细内容】
2023-03-23  Tags: C++  点击:(76)  评论:(0)  加入收藏
▌简易百科推荐
前言JSON是很常用的数据格式,在C++中我们可以使用nlohmann json做序列化和反序列化。 nlohmann json是一个跨平台的开源的C++ JSON解析库,只需要在项目中#include "json.hpp"...【详细内容】
2023-05-22  山城科技峰  今日头条  Tags:C++   点击:(1)  评论:(0)  加入收藏
CefSharp是一个基于Chromium的开源.NET库,可以在C#应用程序中嵌入Web浏览器。以下是使用CefSharp内嵌网页的步骤: 1. 安装CefSharp NuGet包:在Visual Studio中打开NuGet包管理...【详细内容】
2023-05-22  opendotnet  今日头条  Tags:C#   点击:(2)  评论:(0)  加入收藏
前言本文是关于如何创建Rest API C#控制台应用程序的,在此之前,我们必须知道什么是RESTful api。RESTful API是一种应用程序接口(API),它使用HTTP方法请求GET、PUT、POST和DELETE...【详细内容】
2023-05-20  山城科技峰  今日头条  Tags:C#   点击:(1)  评论:(0)  加入收藏
概述命令行参数解析,在写一些命令行的程序时需要用到,args.hxx类似于Python的argparse,但在C++中,它具有静态类型检查,并且速度更快(也允许完全嵌套的组逻辑,而Python的argparse没...【详细内容】
2023-05-19  山城科技峰    Tags:C++   点击:(0)  评论:(0)  加入收藏
当我第一次开始使用 DOS 时,我喜欢 DOS 自带的 BASIC 来编写游戏和其它一些有趣的程序。很长时间后,我才学习 C 编程语言。我马上爱上了使用 C 语言做开发!它是一种简单易懂的...【详细内容】
2023-04-21    Linux中国  Tags: C 语言   点击:(49)  评论:(0)  加入收藏
C++自适应函数符和函数适配器是C++标准库中非常重要的概念,它们为C++程序员提供了更加灵活和高效的编程方式。自适应函数符是指一类函数对象,可以根据输入的参数类型自动推导...【详细内容】
2023-04-14  睿智的海边风浪  今日头条  Tags:C++   点击:(30)  评论:(0)  加入收藏
C++11 中新增了一种智能指针类型 unique_ptr,它是一种独占式的智能指针,用于管理动态分配的对象,并确保在其生命周期结束时正确释放资源。在使用 unique_ptr 时,指针指向的资源...【详细内容】
2023-04-08  睿智的海边风浪  今日头条  Tags:C++   点击:(35)  评论:(0)  加入收藏
第一、四个用途用途一:定义一种类型的别名,而不只是简单的宏替换。可以用作同时声明指针型的多个对象。比如:char* pa, pb; // 这多数不符合我们的意图,它只声明了一个指向字符...【详细内容】
2023-04-03  QT教程    Tags:C   点击:(33)  评论:(0)  加入收藏
众所周知,C++ 中的string使用比较方便。关于C++ 中的string源码实现最近工作中使用C语言,但又苦于没有高效的字符串实现,字符串的拼接和裁剪都比较麻烦,而且每个字符串都需要申...【详细内容】
2023-04-02  Chadwik  今日头条  Tags:C语言   点击:(31)  评论:(0)  加入收藏
C#的应用也比较多,有时候,我们想要研究一下别人的优秀的项目,可能会借助一些非常规手段来学习。下面,我就分享几款开源的C#反编译工具。dnSpydnSpy 是一个用C#开发,开源的调试器...【详细内容】
2023-03-30  自学编程之道  今日头条  Tags:C#   点击:(77)  评论:(0)  加入收藏
站内最新
站内热门
站内头条