[英]How to use unspecified arguments with clap
I want to create a CLI application using the clap library.我想使用 clap 库创建一个 CLI 应用程序。 The problem I have is that I want to use my application like this:我遇到的问题是我想像这样使用我的应用程序:
./my_app file.txt read2.txt -d
The objective is that I can recover in my program in the form of Vec
with file.txt read2.txt
values.目标是我可以在我的程序中以具有file.txt read2.txt
值的Vec
形式恢复。
my code:我的代码:
use clap::{App, load_yaml};
#[derive(Debug)]
enum EFlag {
Debug,
None,
}
#[derive(Debug)]
pub struct Flag {
debug: EFlag,
}
impl Flag {
pub fn new() -> Flag {
Flag {
debug: EFlag::None,
}
}
pub fn fill_flag(&mut self) {
let yaml = load_yaml!("cli.yaml");
let matches = App::from(yaml).get_matches();
match matches.is_present("debug") {
true => self.debug = EFlag::Debug,
_ => self.debug = EFlag::None,
}
// HERE I WANT TO RECEIVE file.txt file2.txt
}
}
fn main() {
let mut flag = Flag::new();
flag.fill_flag();
}
I use the beta version of clap to create a yaml file to manage the flags.我使用 clap 的 beta 版本创建了一个 yaml 文件来管理标志。
the yaml file: yaml 文件:
name: bs-script
version: "1.0.0"
author: Clement B. <clement.bolin@epitech.eu>
about: Write perform, secure and easy script with an Rust script interpretor
args:
- debug:
short: d
long: debug
about: display debug information
To have an argument accept zero-to-many values, you just need to specify multiple: true
.要让参数接受零对多的值,您只需要指定multiple: true
。
- files:
multiple: true
Then to obtain the files you'd use values_of()
along with a collect::<Vec<&str>>()
:然后获取您将使用values_of()
以及collect::<Vec<&str>>()
的文件:
if let Some(files) = matches.values_of("files") {
let files = files.collect::<Vec<_>>();
println!("{:?}", files);
}
// Prints nothing for `cargo run -- -d`
// Prints `["file.txt"]` for `cargo run -- file.txt -d`
// Prints `["file.txt", "read2.txt"]` for `cargo run -- file.txt read2.txt -d`
Here's the complete cli.yaml
:这是完整的cli.yaml
:
name: bs-script
version: "1.0.0"
author: Clement B. <clement.bolin@epitech.eu>
about: Write perform, secure and easy script with an Rust script interpretor
args:
- files:
multiple: true
about: Files
- debug:
short: d
long: debug
about: display debug information
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.