【发布时间】:2021-01-10 03:42:45
【问题描述】:
我试图弄清楚如何使用 Clap 从输入参数动态生成参数。
我试图用 Clap 模拟的是以下 python 代码:
parser = argparse.ArgumentParser()
parser.add_argument("-i", type=str, nargs="*")
(input_args, additional_args) = parser.parse_known_args()
for arg in input_args:
parser.add_argument(f'--{arg}-bar', required=true, type=str)
additional_config = parser.parse_args(additional_args)
以便您可以在命令中执行以下操作:
./foo.py -i foo bar baz --foo-bar foo --bar-bar bar --baz-bar bar
并从第一个参数动态生成附加参数。不确定是否可以在 Clap 中进行,但我认为这可能是因为 Readme 声明您可以使用构建器模式动态生成参数[1]。
所以这是我尝试这样做的天真的尝试。
use clap::{Arg, App};
fn main() {
let mut app = App::new("foo")
.arg(Arg::new("input")
.short('i')
.value_name("INPUT")
.multiple(true)
.required(true));
let matches = app.get_matches_mut();
let input: Vec<_> = matches.values_of("input").unwrap().collect()
for i in input {
app.arg(Arg::new(&*format!("{}-bar", i)).required(true))
}
}
对于!format 生命周期和app.arg,编译器显然不会对你大喊大叫。我最感兴趣的是解决如何为app 生成新参数,然后可以再次匹配。我对 rust 很陌生,所以 Clap 很可能无法做到这一点。
[1] https://github.com/clap-rs/clap
【问题讨论】:
-
不幸的是,根据这个未解决的问题,Clap 目前不支持此功能:github.com/clap-rs/clap/issues/1880
标签: rust command-line-arguments clap