我遇到了与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)
}
}
_ => (),
}
}