繁体   English   中英

如何使用 Clap 将 pipe 字符串转换为 Rust 应用程序解析 args?

[英]How to pipe string into a Rust app parsing args with Clap?

我是 Rust 的新手,我一直在写一些练习应用程序。 我正在尝试使用 Clap 接受命令行 arguments。 下面的代码接受一个字符串和一个数字并将它们打印出来,如下所示:

$ cargo run "this is a test" -n11
this is a test
11

这工作正常,但我希望能够 pipe 输入代替这样的字符串:

$ echo "this is a test" | cargo run -- -n11
this is a test
11

尝试这样做会产生:

error: The following required arguments were not provided:
    <INPUT>

USAGE:
    clap_sample --num <num> <INPUT>

For more information try --help

我可以像这样使用 xargs 解决这个问题:

$ echo "this is a test" | xargs -d '\n' cargo run -- -n11

有没有更好的方法来做到这一点,这样我就可以在仍然使用 -n 选项的同时接受管道中的字符串? 提前致谢。

  use clap::{Arg, App}; 
  
  fn main() {
     let matches = App::new("Clap Sample")
         .arg(Arg::new("INPUT")
             .required(true)
             .index(1))
         .arg(Arg::new("num")
             .short('n')
             .long("num")
             .takes_value(true))
         .get_matches();
 
     let usr_string = matches.value_of("INPUT").unwrap();
     let key: u8 = matches.value_of("num").unwrap()
         .parse()
         .expect("NaN :(");
 
     println!("{}", usr_string);
     println!("{}", key);
 }

额外的问题:如果我 pipe 是一个带有 xargs 的字符串,我可以在字符串中添加换行符(分隔符设置为 \0),它们会反映在 output 中。 如果我在没有 echo 和 xargs 的情况下直接传递它,则 output 中会显示文字 '\n'。 有没有办法在直接运行时表示换行符?

您的代码正在检查 arguments 的命令行,它没有读取标准输入。 使用xargs get 将输入从 pipe 移动到命令行是一个很好的方法。

echo -n "this is a test" | xargs cargo run -- -n11 

您拥有的另一个选择是更改您的程序,以便在没有给出user_string参数的情况下从标准输入读取。 这是阅读标准输入https://doc.rust-lang.org/std/io/struct.Stdin.html的良好起点

您还应该在此处替换unwrap()

 let key: u8 = matches.value_of("num").unwrap()

检查是否给出了参数,因为它不是.required(true)例如

if let Some(key) = matches.value_of("num")

或者也许有一个unwrap_or("0")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM