use std::process::*;use std::env::args;// 实现调用grep命令搜索文件fnmain() {letmut arg_iter =args();// panic if there is no one arg_iter.next().unwrap();let pattern = arg_iter.next().unwrap_or("main".to_string());let pt = arg_iter.next().unwrap_or("./".to_string());let output =Command::new("/usr/bin/grep").arg("-n").arg("-r").arg(&pattern).arg(&pt).output().unwrap_or_else(|e|panic!("wg panic because:{}", e));println!("output:");let st =String::from_utf8_lossy(&output.stdout);let lines = st.split("\n");for line in lines {println!("{}", line); }}
use std::process::*;use std::env::args;// 实现调用grep命令搜索文件fnmain() {letmut arg_iter =args();// panic if there is no one arg_iter.next();let pattern = arg_iter.next().unwrap_or("main".to_string());let pt = arg_iter.next().unwrap_or("./".to_string());let child =Command::new("grep").arg("-n").arg("-r").arg(&pattern).arg(&pt).spawn().unwrap();// 做些其他的事情 std::thread::sleep_ms(1000);println!("{}", "计算很费时间……");let out = child.wait_with_output().unwrap();let out_str =String::from_utf8_lossy(&out.stdout);for line in out_str.split("\n") {println!("{}", line); }}
但是,这个例子和我们预期的并不太一样!
./demo main /home/wayslog/rust/demo/src
/home/wayslog/rust/demo/src/main.rs:5:fn main() {
/home/wayslog/rust/demo/src/main.rs:9: let pattern = arg_iter.next().unwrap_or("main".to_string());
计算很费时间……
use std::process::*;use std::env::args;// 实现调用grep命令搜索文件fnmain() {letmut arg_iter =args();// panic if there is no one arg_iter.next();let pattern = arg_iter.next().unwrap_or("main".to_string());let pt = arg_iter.next().unwrap_or("./".to_string());let child =Command::new("grep").arg("-n").arg("-r").arg(&pattern).arg(&pt)// 设置pipeline.stdout(Stdio::piped()).spawn().unwrap();// 做些其他的事情 std::thread::sleep_ms(1000);println!("{}", "计算很费时间……");let out = child.wait_with_output().unwrap();let out_str =String::from_utf8_lossy(&out.stdout);for line in out_str.split("\n") {println!("{}", line); }}