我正在使用Clap板条箱来解析命令行参数。我定义了一个ls
应该列出文件的子命令。Clap还定义了一个help
子命令,该子命令显示有关应用程序及其使用情况的信息。
如果未提供任何命令,则什么都不会显示,但是在这种情况下,我希望应用程序显示帮助。
我已经试过了这段代码,看起来很简单,但是却行不通:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
我收到app
移动后使用的错误:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
仔细阅读Clap的文档,我发现clap::ArgMatches
返回的C get_matches()
具有一个usage
返回使用部分字符串的方法,但是不幸的是,仅此部分,而没有其他内容。
She*_*ter 12
用途clap::AppSettings::ArgRequiredElseHelp
:
App::new("myprog")
.setting(AppSettings::ArgRequiredElseHelp)
Run Code Online (Sandbox Code Playgroud)
也可以看看:
如果您使用derive而不是builder API,您可以设置shepmaster提到的标志,如下所示:
#[command(arg_required_else_help = true)]
pub struct Cli {
#[clap(short)]
pub init: bool,
Run Code Online (Sandbox Code Playgroud)
另请参阅: https: //docs.rs/clap/latest/clap/_derive/_tutorial/index.html#configuring-the-parser
您还可以将Command::arg_required_else_help
其用作bool
命令本身。
Command::new("rule").arg_required_else_help(true)
Run Code Online (Sandbox Code Playgroud)