当没有提供命令时,Clap 是否有任何直接的方法来显示帮助? [英] Is there any straightforward way for Clap to display help when no command is provided?

查看:52
本文介绍了当没有提供命令时,Clap 是否有任何直接的方法来显示帮助?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Clap crate 来解析命令行参数.我已经定义了一个应该列出文件的子命令 <​​code>ls.Clap 还定义了一个 help 子命令,用于显示有关应用程序及其使用情况的信息.

I'm using the Clap crate for parsing command line parameters. I've defined a subcommand ls that should list files. Clap also defines a help subcommand that displays information about the application and its usage.

如果未提供任何命令,则根本不会显示任何内容,但我希望应用程序在这种情况下显示帮助.

If no command is provided, nothing gets displayed at all, but I want the app to display help in that case.

我试过这段代码,它看起来很简单,但它不起作用:

I've tried this code, which looks pretty straightforward, but it doesn't work:

extern crate clap;

use clap::{App, SubCommand};

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 matches = app.get_matches();

    if let Some(cmd) = matches.subcommand_name() {
        match cmd {
            "ls" => println!("List something here"),
            _ => eprintln!("unknown command"),
        }
    } else {
        app.print_long_help();
    }
}

我收到一个错误:移动后使用了 app:

I get an error that app is used after move:

error[E0382]: use of moved value: `app`
  --> src/main.rs:18:9
   |
10 |     let matches = app.get_matches();
   |                   --- value moved here
...
18 |         app.print_long_help();
   |         ^^^ value used here after move
   |
   = note: move occurs because `app` has type `clap::App<'_, '_>`, which does not implement the `Copy` trait

阅读 Clap 的文档,我发现在 get_matches() 中返回的 clap::ArgMatches 有一个方法 usage 返回使用部分的字符串,但不幸的是,只有这一部分,没有别的.

Reading through the documentation of Clap, I've found that the clap::ArgMatches that's returned in get_matches() has a method usage that returns the string for usage part, but, unfortunately, only this part and nothing else.

推荐答案

使用 clap::AppSettings::ArgRequiredElseHelp:

App::new("myprog")
    .setting(AppSettings::ArgRequiredElseHelp)

另见:

这篇关于当没有提供命令时,Clap 是否有任何直接的方法来显示帮助?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆