【问题标题】:Parse user input String with clap for command line programming使用 clap 解析用户输入字符串以进行命令行编程
【发布时间】:2020-05-26 21:27:24
【问题描述】:

我想创建一个命令行,使用 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
}

基本上,我想知道是否有办法让 Clap 使用预先给定的参数列表?

【问题讨论】:

标签: rust command-line-interface clap


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    这就是我最终完成整个工作的方式:

    首先,我将整个 main 函数放在一个 loop 中,这样它就可以获取命令,并且可以保留在 CLI 中。

    接下来,我通过stdin 获得输入并拆分参数

    // Print command prompt and get command
    print!("> ");
    io::stdout().flush().expect("Couldn't flush stdout");
    let mut input = String::new();
    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>>();
    

    然后我使用 Clap 进行解析,有点像 @harmic 建议的方式

    let matches = App::new("MyApp")
        // ... command line argument options
        .get_matches_from(words);
    

    并使用subcommands 而不是arguments

    例如。

    .subcommand(SubCommand::with_name("list")
        .help("Print namespaces currently tracked in the database."))
    

    整个文件是here,供好奇者参考。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多