我想在 Rust 中执行一个 shell 命令。在 Python 中可以这样做:
import os
cmd = r'echo "test" >> ~/test.txt'
os.system(cmd)
但 Rust 只有 std::process::Command
。如何执行像 cd xxx && touch abc.txt
这样的 shell 命令?
每个人都在寻找:
use std::process::Command;
fn main() {
let output = Command::new("echo")
.arg("Hello world")
.output()
.expect("Failed to execute command");
assert_eq!(b"Hello world\n", output.stdout.as_slice());
}
要获取更多信息和示例,请参阅文档。
您想模拟 &&
。 std::process::Command
具有返回Result<T>
的status
方法,而 Result
实现了and_then
。 您可以像使用 &&
一样使用 and_then
,但以更安全的Rust方式 :)
如果您想要在编程中使用libc
,那么您可以像在普通的C语言中一样使用system
调用。这被视为FFI,因此您可能需要查看std::ffi::CStr
。
对于任何想设置子进程运行命令的当前目录(比如在某个目录下运行“ls”)的人,可以使用Command::current_dir
。用法:
use std::process::Command;
Command::new("ls")
.current_dir("/bin")
.spawn()
.expect("ls command failed to start");
Command::new("cd").arg("foo").status().success()
,否则Command::new("cd").arg("foo").status()
将总是失败的。 - Jmbcd
不是一个可执行文件,而是一个内部的shell命令,所以不能直接从非shell程序中运行它。你可以使用Command::new ("/bin/sh").args (&["-c", "cd", "foo"])
在shell中运行该命令,但这只是一个无操作(no-op)操作,不会影响调用进程。 - Jmb