같은 시스템 명령을 호출 할 수있는 방법이 있나요 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.
std::io::process. 대신 참조하십시오 (아래 답변).
std::processrustc 1.19.0의로 지금.
output프로세스가 완료되면 함수가 Vec을 반환 한다고 생각 합니다. 그래서 만약 우리가Command("ping google.com"). 완료되지는 않지만 로그를 인쇄하고 싶기 때문에이 명령 출력을 얻을 수 있습니까? 제안 해주세요.