首先,我是 Rust 新手。
最近,我想编写一些 Rust 代码,帮助我在每个前端项目中自动切换节点版本。
所以,我阅读了一些 Rust 文档,我选择
std::process::Command
方法来执行一些 shell 脚本。
看起来像:
use std::process::Command;
fn main() {
let output = Command::new("nvm")
.args(&["--version"])
.output()
.expect("faile");
}
我在上面
cargo run
,收到错误:faile: Os { code: 2, kind: NotFound, message: "No such file or directory" }'
。
但我运行 nvm --version
可以在我的终端中运行。太混乱了...
正如 isaactfa 提到的,nvm 不是一个程序,而是一个 shell 脚本,因此,默认的 rust
std::process::Command
将无法在其上正确运行。
这与 Windows 不同,您当前的代码可以在 Windows 中运行。
但是,有一个解决方法。您可以使用 cmd_lib 箱。有两种方法,但都非常hacky。
第一种方法是使用 shell 脚本部署程序。如果您只打算在本地使用,这是一个不错的方法。
首先在 crate 根目录创建一个 get_nvm.sh (当不运行时需要将其放置在执行文件中
cargo run
)。
get_nvm.sh
export NVM_DIR=$HOME/.nvm;
source $NVM_DIR/nvm.sh;
nvm --version
通过
cargo add cmd_lib
添加cmd_lib后,可以使用:
main.rs
use cmd_lib::run_fun;
fn main() {
let out = run_fun!(bash get_nvm.sh);
}
第二种方法是创建 shell 脚本然后运行它(也可以选择删除它)。这意味着需要分发的只是可执行文件。
main.rs
use std::{fs::{File, remove_file}, io::Write};
use cmd_lib::run_fun;
fn main() {
// Create and write the lines to the file
let mut file = File::create("./get_nvm.sh").unwrap();
file.write_all(
r#"export NVM_DIR=$HOME/.nvm;
source $NVM_DIR/nvm.sh;
nvm --version"#.as_bytes()
).unwrap();
// Run the file
let out = run_fun!(bash get_nvm.sh);
// OPTIONAL: Delete the file
remove_file("./get_nvm.sh").unwrap();
}