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 项目目录路径。

相关推荐
传奇开心果编程11 分钟前
【Rust入门练中学】第5课:引用与借用
开发语言·rust·引用·编程语言理论·通用编程语言·借用
码林鼠2 小时前
flutter状态管理入门教程-Riverpod
开发语言·javascript·flutter
码林鼠5 小时前
flutter网络http请求入门教程-dio
网络协议·flutter·http
geovindu5 小时前
rust: Mediator Pattern
开发语言·后端·设计模式·rust·中介者模式·行为模式
传奇开心果编程5 小时前
【Rust入门练中学】第8课:错误处理
开发语言·rust·错误处理·编程语言理论·通用编程语言
码林鼠6 小时前
flutter BLoC 单向数据流完整教程
flutter
传奇开心果编程7 小时前
【Rust入门练中学】第9课:集合类型
开发语言·rust·编程语言理论·集合类型·通用编程语言
人人都是软件工程师8 小时前
📚 Tesla AI 总监:让 LLM 把文档"编译"成持续生长的知识库 llm_wiki
人工智能·rust·开源
dennislee6668 小时前
项目一多,终端标签就失控了:我用 Rust 写了个 macOS 启动工作台,还让 AI 能自己重启服务
rust
Amos_Web9 小时前
通过 Rspack 源码学 Rust(零):Cargo workspace 与统一依赖版本
rust