首页 > 系统相关 >rust运行shell命令并获取输出

rust运行shell命令并获取输出

时间:2024-09-28 13:47:47浏览次数:1  
标签:输出 shell unwrap new let arg output rust out

use std::io::{BufReader, BufRead};
use std::process::{self, Command, Stdio};

fn main() {
    ls();
    ps();
    xargs();
    time();
    iostat();
}

// 不带参数命令
fn ls() {
    let output = Command::new("ls").output().expect("执行异常,提示");
    let out = String::from_utf8(output.stdout).unwrap();
    println!("{}", out);
}

// 带参数命令
fn ps() {
    // ps -q $$ -o %cpu,%mem
    let output = Command::new("ps")
        .arg("-q")
        .arg(process::id().to_string())
        .arg("-o")
        .arg("%cpu,%mem")
        .output()
        .unwrap();
    let out = String::from_utf8(output.stdout).unwrap();
    println!("{}", out);
}

// 复杂命令,直接扔进bash执行
fn xargs() {
    let mut cmd = "cat /proc/".to_string();
    cmd += &process::id().to_string();
    cmd += &"/stat | awk '{print $14,$15,$16,$17}'".to_string();
    let output = Command::new("bash")
        .arg("-c")
        .arg(cmd)
        .output()
        .unwrap();
    let out = String::from_utf8(output.stdout).unwrap();
    println!("utime stime cutime cstime");
    println!("{}", out);
}

// 手动实现管道
fn time() {
    let mut fname = "/proc/".to_string();
    fname += &process::id().to_string();
    fname += &"/stat".to_string();
    let child = Command::new("cat")
        .arg(fname)
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let output = Command::new("awk")
        .arg("{print $14,$15,$16,$17}")
        .stdin(child.stdout.unwrap())
        .output()
        .unwrap();
    let out = String::from_utf8(output.stdout).unwrap();
    println!("utime stime cutime cstime");
    println!("{}", out);
}

// 获取运行中的命令的输出
fn iostat() {
    let child = Command::new("iostat")
        .arg("1")
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let mut out = BufReader::new(child.stdout.unwrap());
    let mut line = String::new();
    while let Ok(_) = out.read_line(&mut line) {
        println!("{}", line);
    }
}

参考文献:

rust:执行shell命令
https://stackoverflow.com/questions/40836973/unable-to-use-stdprocesscommand-no-such-file-or-directory
https://www.reddit.com/r/rust/comments/3azfie/how_to_pipe_one_process_into_another/

标签:输出,shell,unwrap,new,let,arg,output,rust,out
From: https://www.cnblogs.com/searchstar/p/18437581

相关文章

  • rust打印变量类型
    可以试试std::any::type_name。注意,这个是unstable的。usestd::collections::HashSet;fnprint_type_of<T>(_:&T){println!("{}",std::any::type_name::<T>())}fnmain(){letmuts=HashSet::new();letve=vec![1,2,1,3,2,......
  • rust交换数组中的两个元素
    不可以直接用std::mem::swap,因为这个函数需要拿两个可变引用,但是不可以同时拿两个这个数组的可变引用。所以要么手写:lettmp=a[i];a[i]=a[j];a[j]=tmp;要么用Vec::swap:a.swap(i,j);其内部实现:fnswap(&mutself,a:usize,b:usize){unsafe{//......
  • rust二分搜索
    如果要二分搜索某个特定值,可以用binary_search:https://doc.rust-lang.org/stable/std/primitive.slice.html#method.binary_search如果要实现C++里的lower_bound和upper_bound类似的功能,可以用partition_point:https://doc.rust-lang.org/stable/std/primitive.slice.html#meth......
  • Rust索引String
    Rust的String里其实是UTF-8编码的,而UTF-8是变长编码,因此会导致Rust索引String时,可能是索引第k个UTF-8字符(需要遍历字符串),也可能是索引第k个字节。因此,Rust不支持直接用下标来索引String。如果要找到第k个UTF-8字符:s.chars().nth(k)如果要找到第k个字节:letx:u8=s.as_bytes......
  • 实验1 c语言输入输出和简单程序编写
    任务1:task1.11#include<stdio.h>2345intmain()6{7printf("o\n");8printf("<H>\n");9printf("II\n");10printf("o\n"......
  • 【C语言标准库函数】标准输入输出函数详解2:字符串输入输出
    目录一、字符串输入函数1.1.gets函数(已废弃)1.1.1.函数简介1.1.2.注意和废弃原因1.2.fgets函数1.2.1.函数简介1.2.2.使用场景1.2.3.注意事项1.2.4.示例二、字符串输出函数2.1.puts函数2.1.1.函数简介2.1.2. 使用场景2.1.3.注意事项2.1.4.示例2.2.......
  • 输入输出返回值
    大部分情况下,输入输出函数返回值没有被特别关注,但在某些情况下,这些返回值格外有研究意义。返回值的不同形态C语言printf和scanf返回值分别为输出字节个数以及成功输入的变量个数。大部分情况下,printf返回个数并不关心,可以在调用函数前面加(void)强制忽略返回值。ObjC相......
  • PowerShell 脚本禁用 Realtek Audio Console 中的前面板插孔检测,通常需要修改注册表项
     PowerShell脚本禁用RealtekAudioConsole中的前面板插孔检测,通常需要修改注册表项。以下是一个示例脚本,用于执行此操作:powershellCopyCode#设置注册表路径$registryPath="HKLM:\SOFTWARE\Realtek\Audio\RtkNGUI\Settings"#检查注册表路径是否存在if(-not(Test-......
  • Python基础04_Python字符串(下)&Python输入和输出&条件语句&循环语句&pass语句
    目录Python字符串(下)6、字符串的常用函数APIPython输入和输出1、输出 2、输入条件语句1.if2、if-else3、if-elif-else循环语句1、range函数2、for-in循环3、while循环4、循环控制break:用于 跳出 当前循环: continue:用于跳过当前迭代,继续下一次迭代:5、p......
  • 实验1 C语言输入输出和简单程序编写
    任务11#include<stdio.h>2intmain()3{4printf("00\n");5printf("<H><H>\n");6printf("IIII");78return0;9} 1#include<stdio.h>2intmain()3{4......