clap教程:第0章

原始示例代码

clap::_derive::_tutorial::chapter_0 - Rust - https://docs.rs/

use std::path::PathBuf;

use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(version, about, long_about = None)]
struct Cli {
    /// Optional name to operate on
    name: Option<String>,

    /// Sets a custom config file
    #[arg(short, long, value_name = "FILE")]
    config: Option<PathBuf>,

    /// Turn debugging information on
    #[arg(short, long, action = clap::ArgAction::Count)]
    debug: u8,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// does testing things
    Test {
        /// lists test values
        #[arg(short, long)]
        list: bool,
    },
}

fn main() {
    let cli = Cli::parse();

    // You can check the value provided by positional arguments, or option arguments
    if let Some(name) = cli.name.as_deref() {
        println!("Value for name: {name}");
    }

    if let Some(config_path) = cli.config.as_deref() {
        println!("Value for config: {}", config_path.display());
    }

    // You can see how many times a particular flag or argument occurred
    // Note, only flags can have multiple occurrences
    match cli.debug {
        0 => println!("Debug mode is off"),
        1 => println!("Debug mode is kind of on"),
        2 => println!("Debug mode is on"),
        _ => println!("Don't be crazy"),
    }

    // You can check for the existence of subcommands, and if found use their
    // matches just as you would the top level cmd
    match &cli.command {
        Some(Commands::Test { list }) => {
            if *list {
                println!("Printing testing lists...");
            } else {
                println!("Not printing testing lists...");
            }
        }
        None => {}
    }

    // Continued program logic goes here...
}

代码解释

use std::path::PathBuf;

use clap::{Parser, Subcommand};

使用clapParser特性为Cli结构体自动生成解析器。这里用来定义命令行参数。

#[derive(Parser)] 

Cli结构体添加一个命令。你可以提供版本信息、命令描述和长描述。

#[command(version, about, long_about = None)]

name:一个可选的名称,用于在命令行中操作。
#[arg]:定义命令行参数。你可以指定短选项、长选项、值的名称和是否需要值。
#[command(subcommand)]:定义子命令。

struct Cli {
    /// Optional name to operate on
    name: Option<String>,

    /// Sets a custom config file
    #[arg(short, long, value_name = "FILE")]
    config: Option<PathBuf>,

    /// Turn debugging information on
    #[arg(short, long, action = clap::ArgAction::Count)]
    debug: u8,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]:使用clapSubcommand特质为Commands枚举自动生成解析器。你可以在这里定义子命令。
Commands:枚举,表示子命令。
Test:枚举值,表示测试子命令。
#[arg]:定义测试子命令的参数。你可以指定短选项、长选项和是否需要值。
list:一个布尔类型的参数,表示是否列出测试值。

#[derive(Subcommand)]
enum Commands {
    /// does testing things
    Test {
        /// lists test values
        #[arg(short, long)]
        list: bool,
    },
}

main函数中,首先创建了一个Cli实例,并使用parse方法解析命令行参数。然后,根据需要访问解析后的参数值。
在示例中,检查了nameconfigdebug的参数值,并根据debug的值输出相应的消息。接着检查是否存在子命令,并根据子命令的参数值执行相应的操作。在示例中,检查了Test子命令的list参数的值,并输出相应的消息。

fn main() {
    let cli = Cli::parse();

    // You can check the value provided by positional arguments, or option arguments
    if let Some(name) = cli.name.as_deref() {
        println!("Value for name: {name}");
    }

    if let Some(config_path) = cli.config.as_deref() {
        println!("Value for config: {}", config_path.display());
    }

    // You can see how many times a particular flag or argument occurred
    // Note, only flags can have multiple occurrences
    match cli.debug {
        0 => println!("Debug mode is off"),
        1 => println!("Debug mode is kind of on"),
        2 => println!("Debug mode is on"),
        _ => println!("Don't be crazy"),
    }

    // You can check for the existence of subcommands, and if found use their
    // matches just as you would the top level cmd
    match &cli.command {
        Some(Commands::Test { list }) => {
            if *list {
                println!("Printing testing lists...");
            } else {
                println!("Not printing testing lists...");
            }
        }
        None => {}
    }

    // Continued program logic goes here...
}

输出解释

官方给出的输出:

$ 01_quick_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 01_quick_derive[EXE] [OPTIONS] [NAME] [COMMAND]

Commands:
  test  does testing things
  help  Print this message or the help of the given subcommand(s)

Arguments:
  [NAME]  Optional name to operate on

Options:
  -c, --config <FILE>  Sets a custom config file
  -d, --debug...       Turn debugging information on
  -h, --help           Print help
  -V, --version        Print version

运行01_quick_derive --help时,打印出命令行参数的帮助信息。这个帮助信息是通过#[command]属性中的aboutlong_about字段生成的。它提供了程序的简要描述、用法说明、命令列表、参数说明和选项说明。

$ 01_quick_derive
Debug mode is off

运行01_quick_derive时,由于没有提供任何命令行参数,所以程序会执行默认逻辑,即不执行任何操作。在示例中,它打印出了Debug mode is off,表示调试模式处于关闭状态。

$ 01_quick_derive -dd test
Debug mode is on
Not printing testing lists...

运行01_quick_derive -dd test时,会根据提供的命令行参数执行相应的操作。在这个例子中,它设置了调试模式为打开状态(通过-d选项),并且执行了测试子命令(通过test命令)。由于测试子命令的list参数没有被提供,所以它打印出了Not printing testing lists...,表示不会打印测试列表。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值