같은 시스템 명령을 호출 할 수있는 방법이 있나요 ls또는 fuser녹는? 출력을 캡처하는 것은 어떻습니까?
답변
std::process::Command 허용합니다.
자식 프로세스를 생성하고 컴퓨터에서 임의의 명령을 실행하는 방법에는 여러 가지가 있습니다.
spawn— 프로그램을 실행하고 세부 사항이있는 값을 리턴합니다.output— 프로그램을 실행하고 출력을 반환합니다.status— 프로그램을 실행하고 종료 코드를 반환합니다.
문서의 간단한 예 :
use std::process::Command;
Command::new("ls")
        .arg("-l")
        .arg("-a")
        .spawn()
        .expect("ls command failed to start");
답변
문서 의 매우 명확한 예 :
use std::process::Command;
let output = Command::new("/bin/cat")
                     .arg("file.txt")
                     .output()
                     .expect("failed to execute process");
println!("status: {}", output.status);
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success());
답변
정말 가능합니다! 관련 모듈은 std::run입니다.
let mut options = std::run::ProcessOptions::new();
let process = std::run::Process::new("ls", &[your, arguments], options);
ProcessOptions‘표준 파일 설명 자의 기본값은None (새 파이프 생성)이므로 process.output()(예를 들어) 출력에서 읽을 수 있습니다.
당신이 명령을 실행하고 당신이 일을 끝낼 후 모든 출력을 얻고 싶은 경우에, 거기에 wait_with_output그것을 위해 .
Process::new어제부터는 Option<Process>대신 a를 반환합니다 Process.
