使用 clap 解析用户输入字符串以进行命令行编程

Wil*_*ges 7 command-line-interface rust clap

我想创建一个利用 clap 来解析输入的命令行。我能想到的最好的办法是一个循环,要求用户输入,用正则表达式将其分解并构建一个 Vec,并以某种方式传递给它

loop {
    // Print command prompt and get command
    print!("> "); io::stdout().flush().expect("Couldn't flush stdout");

    let mut input = String::new(); // Take user input (to be parsed as clap args)
    io::stdin().read_line(&mut input).expect("Error reading input.");
    let args = WORD.captures_iter(&input)
           .map(|cap| cap.get(1).or(cap.get(2)).unwrap().as_str())
           .collect::<Vec<&str>>();

    let matches = App::new("MyApp")
        // ... Process Clap args/subcommands
    .get_matches(args); //match arguments from CLI args variable
}
Run Code Online (Sandbox Code Playgroud)

基本上,我想知道是否有一种方法可以指示 Clap 使用预先给定的参数列表?

har*_*mic 7

正如 @mcarton 所说,命令行程序将其参数作为数组而不是字符串传递。shell 分割原始命令行(考虑引号、变量扩展等)。

如果您的要求很简单,您可以简单地将字符串拆分为空格并将其传递给 Clap。或者,如果您想尊重带引号的字符串,您可以使用shellwords来解析它:

let words = shellwords::split(input)?;
let matches = App::new("MyApp")
    // ... command line argument options
    .get_matches_from(words);
Run Code Online (Sandbox Code Playgroud)