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

问题描述 投票:0回答:1

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

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

rust clap
1个回答
2
投票

您可以在之前编写字符串。

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)
            }
        }
        _ => (),
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.