如何将带有多个参数的单个字符串传递给std :: process :: Command? [英] How do I pass a single string with multiple arguments to std::process::Command?

查看:87
本文介绍了如何将带有多个参数的单个字符串传递给std :: process :: Command?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust的 std :: process :: Command 类型要求通过 .arg(-arg1)。arg分别传递过程参数。 ( -arg2)或通过 .args(& [-arg1, -arg2])作为字符串向量。如何将字符串拆分为可以作为参数传递的向量?

Rust's std::process::Command type demands that process arguments be passed in individually via .arg("-arg1").arg("-arg2") or as a vector of strings via .args(&["-arg1", "-arg2"]). How do you split a string into a vector that can be passed as arguments?

推荐答案

拆分命令行时,shell会做什么?将字符串放入参数绝非易事,尤其是当您想处理诸如引用之类的内容时。例如,您的代码应传递以下断言:

What shells do when splitting a command-line string into arguments is far from trivial, especially when you want to handle things like quoting. For example, your code should pass the following assertions:

assert_eq!(split(r#""foo\"bar""#), vec!["foo\"bar"]);
assert_eq!(split(r#""foo"#), vec!["\"foo"]);          // Or error

除非您认为简单地在空格上拆分就足以满足您的用例,否则您应该确实使用了 shell-words shlex shlex 的优点是它可以返回迭代器,从而避免了不必要的分配,但另一方面,它很容易错过上面第二个测试中的错误:

Unless you think simply splitting on whitespace is enough for your use-case, you should really use a crate like shell-words or shlex. shlex presents the advantage that it can return an iterator, thus avoiding unnecessary allocations, but on the other hand it makes it easy to miss the error in the second test above:

extern crate shell_words;
extern crate shlex;

use shell_words::split;
use shlex::Shlex;

fn main() {
    assert_eq!(split(r#"a b"#).unwrap(), vec!["a", "b"]);
    let mut lex = Shlex::new(r#"a b"#);
    assert_eq!(lex.by_ref().collect::<Vec<_>>(), vec!["a", "b"]);
    assert!(!lex.had_error);    // ← Don't forget this check!

    assert_eq!(split(r#"a "b c""#).unwrap(), vec!["a", "b c"]);
    let mut lex = Shlex::new(r#"a "b c""#);
    assert_eq!(lex.by_ref().collect::<Vec<_>>(), vec!["a", "b c"]);
    assert!(!lex.had_error);    // ← Don't forget this check!

    assert_eq!(split(r#""foo\"bar""#).unwrap(), vec!["foo\"bar"]);
    let mut lex = Shlex::new(r#""foo\"bar""#);
    assert_eq!(lex.by_ref().collect::<Vec<_>>(), vec!["foo\"bar"]);
    assert!(!lex.had_error);    // ← Don't forget this check!

    assert!(split(r#""foo"#).is_err());
    // assert_eq!(Shlex::new(r#""foo"#).collect::<Vec<_>>(), vec!["\"foo"]);

    let mut lex = Shlex::new(r#""foo"#);
    lex.by_ref().for_each (drop);
    assert!(lex.had_error);     // ← Don't forget this check!
}

这篇关于如何将带有多个参数的单个字符串传递给std :: process :: Command?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆