3 个版本
| 0.1.2 | 2024 年 3 月 23 日 |
|---|---|
| 0.1.1 | 2024 年 3 月 23 日 |
| 0.1.0 | 2024 年 3 月 19 日 |
#2 in #shell-like
20KB
391 代码行(不含注释)
在调用 std::process::Command 时,可以删除很多杂乱无章的样板代码。
宏
使用 cmd! 宏创建 std::process:Command 结构体,使用 exec! 和 run! 直接通过 status() 和 output() 分别执行它们。
run!(echo "Hello World!");
# equivalent to
Command::new("echo").arg("Hello World1").output();
默认情况下,所有参数都将被视为空格分隔的字符串。如果您的参数包含空格,请将其用引号括起来,如上所示。
要使用现有变量作为参数,请将变量的名称用花括号括起来。您可以混合不同类型的参数(与 .args() 方法不同)。
run!(echo (some_str) (some_string) (some_path));
# equivalent to
Command::new("echo").arg(some_str).arg(some_string).arg(some_path).output();
如果您的变量是可迭代的,您可以使用 .. 来展开它。
run!(echo Hello (worlds..))
如果您的参数是可选的,您可以使用 ? 来仅将其附加到值为 Some 的情况下。
let name = Some("Steve");
run!(echo Hello (name ?));
如果您在相同的花括号内包含一个字面量,该字面量也仅当值为 Some 时才包含(用于标志)。这也适用于可迭代对象。
let packages = vec!["cowsay", "emacs"];
run!(echo Installing ("-p" packages ?));
使用 args! 宏将参数附加到现有 Command,使用与 cmd! 相同的语法。
fn my_function(mut cmd: Command) -> Command {
cmd.args(args!(some new args here));
cmd
}
扩展
在 status() 或 output() 的返回值上使用 cmd_ok() 方法来创建一个 Err(),它在 IO 失败和任何退出代码(除了 0)的情况下都会出现,后者将包括 stderr 的内容(如果可用)。
run!(echo test).cmd_ok()?
使用 opt_arg 向您的命令传递可选值,并且只有在它们是 Some 时才使用它们。
请使用 output.stdout()、output.stderr()、output.stdout_lossy() 和 output.stderr_lossy() 来替代 String::from_utf8(output.stdout)。
依赖关系
~120KB