std::process

最後更新


啟動並控制外部程式,以及結束目前的程式並回報結束碼。

這個模組做什麼


有時候最快的做法是直接呼叫系統上現成的工具:跑 git 查版本、呼叫壓縮程式、執行一段 shell 指令。std::process 的 Command 就是 Rust 版的「在終端機打指令」,而且能拿到輸出、餵入資料、檢查成功與否。
另一半功能是控制自己怎麼結束:process::exit 立即終止,ExitCode 讓 main 回傳結束碼給呼叫者(shell、CI 系統)。
需求用什麼
執行並取得全部輸出Command::output()
執行並只看成功與否(輸出直接顯示)Command::status()
邊跑邊互動、串接管線Command::spawn() + Stdio::piped()
立即結束程式process::exit(code)
讓 main 回傳結束碼ExitCode

匯入


  1. use std::process::{self, Command, ExitCode, Stdio};

本頁範例呼叫 echo、printf、printenv、sort、wc、sh、true、false,在 macOS 與 Linux 都有。Windows 沒有這些獨立程式(echo 是 cmd.exe 的內建指令),要寫成 Command::new("cmd").args(["/C", "echo hello"])。

常用 API


Command::new 與 output:執行並收集輸出


Command::new 指定要執行的程式,arg/args 加上參數,最後呼叫 output():它會等程式跑完,把標準輸出、標準錯誤收集成 Vec<u8>,連同結束狀態一起放在 Output 裡。
Command 不經過 shell,參數直接交給程式,所以不需要處理引號跳脫,也不會被 shell 解讀 *、$ 這些特殊字元。
簽名:
  1. pub fn new<S: AsRef<OsStr>>(program: S) -> Command;
  2. pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Command;
  3. pub fn output(&mut self) -> io::Result<Output>;

注意:output() 回傳 Ok 只代表程式成功啟動並結束,不代表它執行成功;要另外檢查 out.status.success()。輸出是位元組,轉文字用 String::from_utf8_lossy。
範例:
  1. use std::process::Command;
  2. fn main() -> std::io::Result<()> {
  3. let out = Command::new("echo").arg("hello from child").output()?;
  4. println!("success: {}", out.status.success());
  5. println!("stdout: {:?}", String::from_utf8_lossy(&out.stdout));
  6. println!("stderr bytes: {}", out.stderr.len());
  7. Ok(())
  8. }

輸出:
  1. success: true
  2. stdout: "hello from child\n"
  3. stderr bytes: 0

status:只取得結束狀態


status() 執行程式並等待結束,子程式的輸出直接顯示在終端機,回傳 ExitStatus。success() 判斷結束碼是否為 0,code() 取得結束碼;被訊號(signal)終止的程式沒有結束碼,code() 回傳 None。
簽名:
  1. pub fn status(&mut self) -> io::Result<ExitStatus>;
  2. pub fn success(&self) -> bool;
  3. pub fn code(&self) -> Option<i32>;

範例:
  1. use std::process::Command;
  2. fn main() -> std::io::Result<()> {
  3. for prog in ["true", "false"] {
  4. let status = Command::new(prog).status()?;
  5. println!("{:<5} success={} code={:?}", prog, status.success(), status.code());
  6. }
  7. let st = Command::new("sh").args(["-c", "exit 7"]).status()?;
  8. println!("sh exit 7 -> {:?}", st.code());
  9. Ok(())
  10. }

輸出:
  1. true success=true code=Some(0)
  2. false success=false code=Some(1)
  3. sh exit 7 -> Some(7)

args 與 env:參數與環境變數


args 一次加入多個參數;env 替子程式設定環境變數,env_clear 清空所有繼承來的環境變數,current_dir 指定子程式的工作目錄。這些設定只影響子程式,不會改到目前程式自己的環境。
簽名:
  1. pub fn args<I, S>(&mut self, args: I) -> &mut Command
  2. where I: IntoIterator<Item = S>, S: AsRef<OsStr>;
  3. pub fn env<K, V>(&mut self, key: K, val: V) -> &mut Command;
  4. pub fn env_clear(&mut self) -> &mut Command;

注意:env_clear 也會清掉 PATH,之後若程式名稱不是絕對路徑,在某些平台上可能找不到。範例中 printenv 找不到變數時以非 0 結束碼離開,所以 success 是 false。
範例:
  1. use std::process::Command;
  2. fn main() -> std::io::Result<()> {
  3. let out = Command::new("printf")
  4. .args(["%s=%s\n", "name", "Rust 新手"])
  5. .output()?;
  6. print!("{}", String::from_utf8_lossy(&out.stdout));
  7. let out = Command::new("printenv")
  8. .arg("GREETING")
  9. .env("GREETING", "hi there")
  10. .output()?;
  11. print!("{}", String::from_utf8_lossy(&out.stdout));
  12. let out = Command::new("printenv")
  13. .arg("GREETING")
  14. .env_clear()
  15. .output()?;
  16. println!("after env_clear: success={}", out.status.success());
  17. Ok(())
  18. }

輸出:
  1. name=Rust 新手
  2. hi there
  3. after env_clear: success=false

spawn 與 Stdio::piped:管線與互動


spawn() 啟動程式後立刻返回一個 Child,不等它結束。搭配 Stdio::piped(),就能從 child.stdin 寫入資料、從 child.stdout 讀出結果。wait_with_output() 等程式結束並收集剩餘輸出。
把一個子程式的 stdout 轉成 Stdio 交給下一個子程式的 stdin,就等同 shell 的 printf ... | wc -l。
簽名:
  1. pub fn spawn(&mut self) -> io::Result<Child>;
  2. pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Command;
  3. pub fn wait_with_output(self) -> io::Result<Output>;

注意:寫完 stdin 後要讓它被 drop(範例用大括號區塊),子程式才會收到 EOF;否則像 sort 這種要讀完才輸出的程式會一直等,造成死結。spawn 出來的 Child 被 drop 時不會終止子程式,也不會等它,記得 wait。
範例:
  1. use std::io::Write;
  2. use std::process::{Command, Stdio};
  3. fn main() -> std::io::Result<()> {
  4. let mut child = Command::new("sort")
  5. .stdin(Stdio::piped())
  6. .stdout(Stdio::piped())
  7. .spawn()?;
  8. {
  9. let mut stdin = child.stdin.take().expect("stdin is piped");
  10. stdin.write_all(b"pear\napple\nfig\n")?;
  11. }
  12. let out = child.wait_with_output()?;
  13. print!("{}", String::from_utf8_lossy(&out.stdout));
  14. let producer = Command::new("printf")
  15. .arg("one\ntwo\nthree\n")
  16. .stdout(Stdio::piped())
  17. .spawn()?;
  18. let counter = Command::new("wc")
  19. .arg("-l")
  20. .stdin(Stdio::from(producer.stdout.expect("stdout is piped")))
  21. .output()?;
  22. println!("lines: {}", String::from_utf8_lossy(&counter.stdout).trim());
  23. Ok(())
  24. }

輸出:
  1. apple
  2. fig
  3. pear
  4. lines: 3

找不到程式:處理啟動失敗


程式不存在或沒有執行權限時,output()/status()/spawn() 直接回傳 Err,種類通常是 ErrorKind::NotFound。這和「程式有跑起來但回報失敗」是兩件事,要分開處理。
簽名:
  1. pub fn output(&mut self) -> io::Result<Output>;

範例:
  1. use std::io::ErrorKind;
  2. use std::process::Command;
  3. fn main() {
  4. match Command::new("this-command-does-not-exist").output() {
  5. Ok(out) => println!("ran: {}", out.status),
  6. Err(e) if e.kind() == ErrorKind::NotFound => println!("program not found"),
  7. Err(e) => println!("spawn failed: {}", e),
  8. }
  9. }

輸出:
  1. program not found

exit:立即結束程式


process::exit(code) 立刻結束整個行程,並把結束碼交給作業系統。它的回傳型別是 !(never type),代表永遠不會返回。
下面的範例輸出包含標準輸出與標準錯誤(fatal: ... 來自 eprintln!),結束碼是 2,可用 shell 的 echo $? 查看。
簽名:
  1. pub fn exit(code: i32) -> !;

注意:exit 不會執行任何解構子(Drop),範例中的 guard dropped 沒有印出;BufWriter 裡尚未 flush 的資料也會遺失。除非真的需要從深處立即中止,否則優先讓 main 回傳 ExitCode。
範例:
  1. use std::process;
  2. struct Guard;
  3. impl Drop for Guard {
  4. fn drop(&mut self) {
  5. println!("guard dropped");
  6. }
  7. }
  8. fn check(ok: bool) {
  9. if !ok {
  10. eprintln!("fatal: config missing");
  11. process::exit(2);
  12. }
  13. }
  14. fn main() {
  15. let _g = Guard;
  16. println!("checking...");
  17. check(false);
  18. println!("never printed");
  19. }

輸出:
  1. checking...
  2. fatal: config missing

ExitCode:從 main 回傳結束碼


main 可以回傳 ExitCode,程式正常結束、解構子照常執行,最後把結束碼交給作業系統。ExitCode::SUCCESS 是 0,ExitCode::FAILURE 是 1,ExitCode::from(u8) 指定其他值。main 回傳 Result<(), E> 時,Err 會印出錯誤並以 1 結束,也是常見寫法。
下面的範例結束碼是 3,輸出來自標準錯誤。
簽名:
  1. pub const SUCCESS: ExitCode;
  2. pub const FAILURE: ExitCode;
  3. impl From<u8> for ExitCode;

範例:
  1. use std::process::ExitCode;
  2. fn run(input: &str) -> Result<i32, String> {
  3. input.parse::<i32>().map_err(|e| format!("cannot parse {:?}: {}", input, e))
  4. }
  5. fn main() -> ExitCode {
  6. match run("forty-two") {
  7. Ok(n) => {
  8. println!("value = {}", n);
  9. ExitCode::SUCCESS
  10. }
  11. Err(msg) => {
  12. eprintln!("error: {}", msg);
  13. ExitCode::from(3)
  14. }
  15. }
  16. }

輸出:
  1. error: cannot parse "forty-two": invalid digit found in string

重點整理


  • Command 不經過 shell,參數不需要跳脫;需要 shell 功能時明確呼叫 sh -c
  • output() 收集輸出、status() 只看結果、spawn() 用於管線與互動
  • Ok(output) 不等於成功,還要檢查 status.success()
  • 管線寫完 stdin 要 drop 它,否則子程式等不到 EOF
  • process::exit 不執行 Drop;一般情況讓 main 回傳 ExitCode