How do I pass a single string with multiple arguments to std::process::Command?

前端 未结 2 1363
时光取名叫无心
时光取名叫无心 2021-01-18 18:46

Rust\'s std::process::Command type demands that process arguments be passed in individually via .arg(\"-arg1\").arg(\"-arg2\") or as a vector of st

2条回答
  •  走了就别回头了
    2021-01-18 18:55

    Implementation which does not support quoted arguments (but easy to add):

    fn sh(command: &str) -> std::io::Result {
        let mut the_args = command.split(' '); // todo: support quoted strings
        let first: &str = the_args.next().unwrap();
        let rest: Vec<&str> = the_args.collect::>();
        std::process::Command::new(first).args(rest).output()
    }
    
    fn main() {
        let output = sh("ls -la").unwrap(); 
        let s = String::from_utf8_lossy(&output.stdout).to_string();
        println!("{:?}", s);
    }
    

    You have to do quite a bit of song and dance with iterators and string conversions. This tripped me up for a few days. I hope someone can chime in with a basic parser that handles quoted argument strings :).

提交回复
热议问题