【问题标题】:How do I execute a command in a subshell in Rust?如何在 Rust 的子 shell 中执行命令?
【发布时间】:2020-01-28 19:45:54
【问题描述】:

在 Python 中,我可以使用 os.system("pip install bs4")。 Rust 中是否有任何等价物?我见过std::process::Command,但这似乎每次都失败:

use std::process::Command;
Command::new("pip")
    .arg("install")
    .arg("bs4")
    .spawn()
    .expect("pip failed");

有没有办法让代码执行一个真正的 shell 并让它们在终端中运行?

【问题讨论】:

  • Command::new("your-shell-name").args(&["whatever", "you", "need")?
  • 你能提供一个失败的例子吗?

标签: rust command subshell


【解决方案1】:

Pip 需要 root 权限,因此请确保以足够的权限运行您的二进制文件。

以下内容对我有用:

use std::process::Command;
Command::new("pip")
    .args(&["install", "bs4"])
    .spawn()
    .expect("failed to execute process");

用这个来分析失败:

use std::process::Command;
let output = Command::new("pip")
    .args(&["install", "bs4"])
    .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));

示例来自这里:

How do I invoke a system command in Rust and capture its output?

【讨论】:

  • 你永远不应该以 root 身份使用 pip。设置 venv 或使用 pip install --user
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-03
  • 1970-01-01
  • 1970-01-01
  • 2014-06-12
  • 2015-09-26
  • 2010-12-25
  • 2011-08-23
相关资源
最近更新 更多