flutter使用Command库调用cmd命令或者shell命令,并支持多个参数和指定文件夹目录

想要在不同的平台上运行flutter doctor命令,就需要知道对应的平台是windows还是linux,如果是windows就需要调用cmd命令,如果是linux平台,就需要调用sh命令,所以可以通过cfg!实现不同平台的判断,然后调用不同的脚本。

rust 复制代码
use std::process::Command;


pub fn run_cmd() {
    // choice a platform use cfg command
    let flutter_doctor = "pwd";
    let out_put = if cfg!(target_os = "windows") {
        Command::new("cmd").arg("/c").arg(flutter_doctor).output().expect("cmd run error")
    } else {
        Command::new("sh").arg("-c").arg(flutter_doctor).output().expect("shell exec error!")
    };
    let output_str = String::from_utf8_lossy(&out_put.stdout);
    println!("{}", output_str);
}

此时运行上述代码,会打印出当前运行命令所在的文件夹:

可以看到运行的文件夹跑到src-build里面了,这个时候运行flutter doctor肯定是不生效的,当然运行在这个文件夹也是合情合理的,但是我们需要让他跳到外面一层,然后再运行flutter doctor才有效果,所以需要在运行flutter doctor之前,切换文件夹:

rust 复制代码
use std::process::Command;
use std::io::{self, Write};

fn main() {
    // 指定要运行命令的目录
    let flutter_project_dir = "path/to/flutter/project";

    let output = if cfg!(target_os = "windows") {
        // Windows 平台
        Command::new("cmd")
            .args(&["/C", "cd", &flutter_project_dir, "&&", "flutter", "doctor"])
            .output()
            .expect("Failed to execute command")
    } else {
        // macOS 平台
        Command::new("sh")
            .args(&["-c", &format!("cd {} && flutter doctor", &flutter_project_dir)])
            .output()
            .expect("Failed to execute command")
    };

    // 打印命令输出
    io::stdout().write_all(&output.stdout).unwrap();
    io::stderr().write_all(&output.stderr).unwrap();
}

在这个示例中,我们首先指定了要运行命令的目录 flutter_project_dir。然后,我们使用 Command::new("cmd") 来启动 Windows 的命令行解释器,并通过参数 /c 来告诉它执行完后退出。接着,我们使用 cd 命令切换到指定目录,然后执行 flutter doctor 命令。

最后,我们通过 output() 方法获取命令的输出,并将其打印出来。请确保将 path/to/flutter/project 替换为实际的 Flutter 项目目录路径。

相关推荐
Zoom5 小时前
【开源】7 天,我用 Rust 复刻了 FinalShell!Rhost v1.0.0 发布
rust·electron·shell
wflynn9 小时前
GitHub 今日推荐|ts-rust:把微软 TypeScript-Go 编译器逐行移植成 Rust 实现
rust·typescript·开源·github·compiler·tsc
miofly10 小时前
GitHub 今日推荐|wordcraft:用 Rust 重写 Word 内核并开放给 AI 调用
rust·开源·github
陆断枫10 小时前
Flutter 3.47 动画引擎盘点:Impeller 全平台,和那些"新特性"
flutter
Amos_Web10 小时前
Rspack 源码解析(十八):Tree Shaking 如何用 SideEffects 重写模块连接
前端·rust·前端框架
程序员老刘11 小时前
Flet 1.0 思路很好,可惜来晚了
flutter·ai编程·客户端
Source.Liu12 小时前
【A11】Tauri v2 + 原生前端(无框架)项目笔记:从零到登录界面
rust
Kapaseker13 小时前
Rust 1.99.0 发布,来看看这次 Rust 更新了什么
rust
卷无止境16 小时前
用Rust重写:三条清晰的收益曲线
后端·rust
m0_7381858217 小时前
Flutter 鸿蒙化实战:qr_code_scanner_plus 适配 OpenHarmony,二维码扫描
flutter·华为·harmonyos·鸿蒙