简体   繁体   English

如何在 Rust 的子 shell 中执行命令?

[英]How do I execute a command in a subshell in Rust?

In Python, I could do os.system("pip install bs4") .在 Python 中,我可以执行os.system("pip install bs4") Is there any equivalent in Rust? Rust 中是否有任何等价物? I've seen std::process::Command , but this seems to fail each time:我见过std::process::Command ,但这似乎每次都失败:

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

Is there any way to have the code execute a real shell and have them run in the terminal?有没有办法让代码执行一个真正的 shell 并让它们在终端中运行?

Pip requires root permissions so be sure to run your binary with sufficient privileges. Pip 需要 root 权限,因此请确保以足够的权限运行二进制文件。

The following worked for me:以下对我有用:

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

Use this to analyze the failure:使用它来分析故障:

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));

Example was derived from here:示例源自此处:

How do I invoke a system command in Rust and capture its output? 如何在 Rust 中调用系统命令并捕获其输出?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Rust 中执行已实现的方法? - How do I execute an implemented method in Rust? 如何使用 Rust SDK 在 Aptos 上执行 Move 脚本? - How do I execute a Move script on Aptos using the Rust SDK? 在 Rust 中使用 tokio-postgres 调用执行函数之前如何准备查询参数? - How do I prepare query parameters before calling the execute function with tokio-postgres in Rust? Rust闭包如何工作以及如何执行闭包? - How do Rust closures work and how does it execute a closure? 如何以 Rust 语言标准输出到终端执行 std::process::Command - How do I stdout into terminal executing std::process::Command in Rust language 如何在不使用命令行的情况下使用具有 CLAP 的 Rust 板条箱的功能? - How do I use the functionality of a Rust crate that has CLAP without using the command line? 如何使用 rust bindgen 为 postgresql 后端创建 Rust 绑定? - How do I create Rust bindings for the postgresql backend with rust bindgen? 如何在Rust中进行实时编程? - How do I do realtime programming in Rust? 如何在 MacOS 上编译 Rust 以在 AWS EC2 实例上运行? “无法执行二进制文件:Exec 格式错误” - How do I compile Rust on MacOS, to be run on an AWS EC2 instance? "cannot execute binary file: Exec format error" 在 rust 中执行命令时,程序结束 - When execute command in rust, the program finish
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM