rust - 调用 Clap 的 get_matches 后如何显示帮助?

标签 rust clap

我遇到了与 Is there any straightforward way for Clap to display help when no command is provided? 相同的问题,但该问题中提出的解决方案对我来说还不够好。

.setting(AppSettings::ArgRequiredElseHelp) 如果没有提供参数则停止程序,即使没有提供参数我也需要程序继续执行。我需要额外显示的帮助。

最佳答案

你可以写之前的字符串。

use clap::{App, SubCommand};

use std::str;

fn main() {
    let mut app = App::new("myapp")
        .version("0.0.1")
        .about("My first CLI APP")
        .subcommand(SubCommand::with_name("ls").about("List anything"));

    let mut help = Vec::new();
    app.write_long_help(&mut help).unwrap();

    let _ = app.get_matches();

    println!("{}", str::from_utf8(&help).unwrap());
}

或者您可以使用 get_matches_safe

use clap::{App, AppSettings, ErrorKind, SubCommand};

fn main() {
    let app = App::new("myapp")
        .setting(AppSettings::ArgRequiredElseHelp)
        .version("0.0.1")
        .about("My first CLI APP")
        .subcommand(SubCommand::with_name("ls").about("List anything"));

    let matches = app.get_matches_safe();

    match matches {
        Err(e) => {
            if e.kind == ErrorKind::MissingArgumentOrSubcommand {
                println!("{}", e.message)
            }
        }
        _ => (),
    }
}

关于rust - 调用 Clap 的 get_matches 后如何显示帮助?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54837057/

相关文章:

rust - 尝试收集到向量中但失败并返回 "a collection cannot be built over elements of type <...>"

rust - 如果 `write` 不可变, `RwLock` 模式如何工作?

command-line - 如何通过 Clap 将所有命令行参数传递给另一个程序?

rust - clap::App 多次移动所有权的方法调用

rust - 当没有提供命令时,Clap 有什么直接的方法来显示帮助吗?

rust - Rust 是否提供了一个包来执行任意值的黑盒测试?

rust - 如何有效地在Rust中为u64整数找到2的下一个幂?

rust - 将 Option<impl Trait> 转换为 Option<Box<dyn Trait>>

rust - 如何更改采用多个值的 clap 参数中值的名称?

rust - 特质 `std::convert::From<cli::Opts>`未实现