qt-C++笔记之QProcess

news2024/9/22 15:43:04

qt-C++笔记之QProcess

code review!

文章目录

  • qt-C++笔记之QProcess
    • 一.示例:QProcess来执行系统命令ls -l命令并打印出结果
      • 说明
    • 二.示例:QProcess来执行系统命令ls -l命令并打印出结果,代码进一步丰富
    • 三.示例:使用 QProcess 在 Qt 中执行 Bash 脚本并处理参数
    • 四.ChatGPT讲解
        • Including QProcess
        • Creating a QProcess Object
        • Starting a Process
        • Reading Output
        • Writing to the Process
        • Checking if the Process is Running
        • Waiting for the Process to Finish
        • Terminating the Process
        • Getting the Exit Status
        • Example Usage

请添加图片描述

一.示例:QProcess来执行系统命令ls -l命令并打印出结果

在这里插入图片描述
代码

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    // 创建QProcess实例
    QProcess process;

    QString program_middle = "ls";
    QStringList middle_arguments;
    middle_arguments << "-l";
    // 启动进程执行命令
    process.start(program_middle, middle_arguments);

    // 等待进程结束
    process.waitForFinished();

    // 读取并打印进程的标准输出
    QByteArray result = process.readAllStandardOutput();
    qDebug() << result;

    return 0;
}

or

在这里插入图片描述

代码

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    // 创建QProcess实例
    QProcess process;
    // 启动进程执行命令
    process.start("ls", QStringList() << "-l");

    // 等待进程结束
    process.waitForFinished();

    // 读取并打印进程的标准输出
    QByteArray result = process.readAllStandardOutput();
    qDebug() << result;

    return 0;
}

说明

这个简短的示例中:

  • 创建了QProcess对象。
  • 使用start方法执行了ls -l命令。
  • 使用waitForFinished方法等待命令执行完成(请注意,这会阻塞,直到外部命令执行完成)。
  • 读取了命令的标准输出,并使用qDebug打印到控制台。

此代码省略了错误处理和信号/槽连接,适用于简单的同步命令执行。如果你想要异步处理或更复杂的错误处理,你需要采用第一个例子中的更详细的方法。

二.示例:QProcess来执行系统命令ls -l命令并打印出结果,代码进一步丰富

代码应该具有清晰的命名,详细的注释,以及适当的输出信息。下面是修改后的示例:

在这里插入图片描述
代码

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char *argv[]) {
    QCoreApplication app(argc, argv);

    // 设置要执行的命令
    QString listCommand = "ls";
    // 设置命令的参数,以列出/home目录的详细内容
    QStringList listArguments;
    listArguments << "-l" << "/home";

    // 创建一个QProcess对象来运行外部命令
    QProcess directoryLister;

    // 在控制台输出即将执行的命令和参数
    qDebug() << "Executing command:" << listCommand << "with arguments" << listArguments;

    // 使用指定的命令和参数启动外部进程
    directoryLister.start(listCommand, listArguments);

    // 等待进程完成,最多等待2000毫秒
    bool isFinished = directoryLister.waitForFinished(2000);

    // 检查进程是否在规定时间内完成
    if (isFinished) {
        // 如果完成,读取命令的标准输出
        QByteArray output = directoryLister.readAllStandardOutput();
        // 在控制台输出命令的结果
        qDebug() << "Directory listing for /home:\n" << output;
    } else {
        // 如果没有完成,输出超时消息
        qDebug() << "The process did not finish within the specified 2 seconds.";
    }

    // 获取并输出进程的退出码
    int exitCode = directoryLister.exitCode();
    qDebug() << "The process exited with code:" << exitCode;

    return 0;
}

在这个修改后的代码中:

  • 变量app代替了a,表示这是一个应用程序的实例。
  • 变量listCommandlistArguments直观地表示了将被执行的命令及其参数。
  • 对象directoryLister表示一个能够列出目录内容的进程。
  • 注释详细描述了代码的每一个部分,帮助理解每一行代码的作用。
  • 输出信息采用了更加清晰和教育性的语言,适合教科书风格。

三.示例:使用 QProcess 在 Qt 中执行 Bash 脚本并处理参数

1.运行
在这里插入图片描述

2.文件结构

在这里插入图片描述

3.cmd.sh

#!/bin/bash
# 这个脚本接受一个目录作为参数,并列出其内容

DIR=$1

if [ -z "$DIR" ]; then
    echo "Usage: $0 <directory>"
    exit 1
fi

ls $DIR

4.main.cpp
在这里插入图片描述

代码

#include <QCoreApplication>
#include <QDebug>
#include <QProcess>

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    // 创建 QProcess 实例
    QProcess process;

    // 脚本文件的路径
    QString scriptPath = "/home/user/qt_cpp_test/qt_test/cmd.sh";

    // 获取目录参数
    QString directory = "/home/user/qt_cpp_test/qt_test";

    // 运行脚本并传递参数
    process.start(scriptPath, QStringList() << directory);

    // 等待进程结束
    if (!process.waitForFinished()) {
        qDebug() << "The process failed to finish.";
        return 1;
    }

    // 获取进程的输出
    QByteArray output = process.readAll();

    // 打印输出
    qDebug() << output;

    return a.exec();
}

5.qt_test.pro

QT += widgets core
TARGET = qt_test
TEMPLATE = app
SOURCES += main.cpp

四.ChatGPT讲解

QProcess is a class provided by the Qt framework to start external programs and communicate with them. It can be used to start, terminate, and communicate with external programs using standard input/output or through specific channels.

Here’s an overview of how you might use QProcess in a Qt application:

Including QProcess

Before using QProcess, you need to include the QProcess header:

#include <QProcess>
Creating a QProcess Object

You can create a QProcess object like any other object in Qt:

QProcess *process = new QProcess(parent);

The parent is a pointer to a parent QObject, which takes ownership of the QProcess object, ensuring that it will be deleted when the parent is.

Starting a Process

You can start a process by calling the start method, providing the command and arguments to run:

process->start("executable", QStringList() << "arg1" << "arg2");

Or if you just need to execute a command without arguments:

process->start("executable");
Reading Output

You can read the standard output and error of the process:

QObject::connect(process, &QProcess::readyReadStandardOutput, [=]() {
    QByteArray standardOutput = process->readAllStandardOutput();
    // Process standard output here
});

QObject::connect(process, &QProcess::readyReadStandardError, [=]() {
    QByteArray standardError = process->readAllStandardError();
    // Process standard error here
});
Writing to the Process

You can write to the standard input of the process:

process->write("input data");
Checking if the Process is Running

You can check if the process is still running:

if (process->state() == QProcess::Running) {
    // Process is running
}
Waiting for the Process to Finish

You can wait synchronously for the process to finish:

process->waitForFinished(); // Waits until the process has finished
Terminating the Process

You can terminate the process:

process->terminate(); // Sends a terminate signal

Or kill the process:

process->kill(); // Kills the process immediately
Getting the Exit Status

Once the process has finished, you can get the exit status:

int exitCode = process->exitCode();
QProcess::ExitStatus exitStatus = process->exitStatus();
Example Usage

Here’s a simple example of using QProcess to run a command and print its output:

#include <QCoreApplication>
#include <QProcess>
#include <QDebug>

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    QProcess process;
    process.start("ls", QStringList() << "-l" << "/");

    if (!process.waitForStarted()) // Default timeout is 30 seconds
        return 1;

    if (!process.waitForFinished()) // Default timeout is 30 seconds
        return 2;

    qDebug() << process.readAllStandardOutput().trimmed();

    return a.exec();
}

This example runs the ls -l / command, which lists the contents of the root directory in a detailed format, then prints the output. Remember that the waitForStarted() and waitForFinished() methods are blocking calls; in a GUI application, you would typically connect the finished() signal to a slot to handle the process completion asynchronously.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1365584.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

ROS+moveit+jakaminicob仿真运动

先浅浅的放一个官方的c文档&#xff1a; Motion Planning API — moveit_tutorials Melodic documentation 目录 一、实现运动到目标点的程序 二、在rviz里面新建扫描平台 一、实现运动到目标点的程序 &#xff08;等我得空了补一个c运行环境部署说明&#xff09; #inclu…

天线选型的关注点

一、一般注意事项 频段 常用频段为&#xff1a; 2.4GHz&#xff5e;2.5GHz&#xff0c; 5.15GHz&#xff5e;5.85GHz&#xff0c;以及双频。增益 内置天线主要关注对所需要的面的覆盖情况&#xff0c;外置天线主要关注水平面的增益要求&#xff0c;常见外置天…

Java面向对象(抽象类,接口,内部类)

文章目录 今日内容教学目标 第一章 抽象类1.1 概述1.1.1 抽象类引入 1.2 abstract使用格式1.2.1 抽象方法1.2.2 抽象类1.2.3 抽象类的使用 1.3 抽象类的特征1.4 抽象类的细节1.5 抽象类存在的意义 第二章 接口2.1 概述2.2 定义格式2.3 接口成分的特点2.3.1.抽象方法2.3.2 常量2…

网络技术基础入门全套实验-厦门微思网络CCNA实验手册

知识改变命运&#xff0c;技术就是要分享&#xff0c;有问题随时联系&#xff0c;免费答疑&#xff0c;欢迎联系&#xff01; 微思简介&#xff08;https://www.xmws.cn) 微思成立于2002年&#xff0c;是一个诚信敬业、积极向上、充满活力、专注技术服务的企业。 微思获得了八…

什么是短视频矩阵系统?效果是怎么样的?

短视频矩阵系统是一种通过将多个短视频连接起来形成一个整体的系统。它的效果是可以提供一种连贯而有序的观看体验&#xff0c;使观众可以连续地观看一系列相关的短视频内容。 短视频矩阵系统的运作方式如下&#xff1a;首先&#xff0c;用户在平台上选择一个短视频开始观看。…

小型洗衣机什么牌子好?迷你洗衣机品牌推荐

随着现代社会的快速发展&#xff0c;洗衣机已经成为了家家必备的电器产品。但是我们清洗贴身衣物的话&#xff0c;并不能直接扔进洗衣机里面洗&#xff0c;主要原因就是会与其他的衣物产生交叉的感染&#xff0c;而且又不能更好地除去贴身衣物上的细菌&#xff0c;因此一台内衣…

Visual Studio 2013 “即将退休”

新年快乐&#xff01; 这也是向各位开发者提醒 Visual Studio 支持生命周期中即将到来的好时机。 对 Visual Studio 2013 的支持即将在今年(2024年)的4月9日结束。如果你正在使用旧版本的 Visual Studio&#xff0c;我们强烈建议您升级您的开发环境到最新的 Visual Studio 20…

StarRocks Awards 2023 年度贡献人物

2023 年行将结束。这一年&#xff0c;StarRocks 继续全方位大步向前迈进&#xff0c;在 300 贡献者的辛勤建设下&#xff0c;社区先后发布了 50 版本&#xff0c;并完成了从全场景 OLAP 到云原生湖仓的进化。 贡献者们的每一行代码、每一场布道&#xff0c;推动着 StarRocks 社…

京东商品详情API接口(item_get-获得JD商品详情)电商领域的重要角色

电商API接口在电商领域中扮演着重要的角色&#xff0c;它们为电商平台提供了许多功能和便利。以下是电商API接口的一些主要用途&#xff1a; 商品信息查询&#xff1a;通过API接口&#xff0c;第三方开发者或商家可以查询电商平台上的商品信息&#xff0c;包括商品详情、价格、…

字节跳动机器人研究团队:用大规模视频数据训练GR-1,机器人轻松应对复杂任务

最近 GPT 模型在 NLP 领域取得了巨大成功。GPT 模型首先在大规模的数据上预训练&#xff0c;然后在特定的下游任务的数据上微调。大规模的预训练能够帮助模型学习可泛化的特征&#xff0c;进而让其轻松迁移到下游的任务上。 但相比自然语言数据&#xff0c;机器人数据是十分稀…

k8s yaml文件pod的生命周期

Pod是k8s中最小限额资源管理组件&#xff0c;也是最小化运行容器化的应用的资源管理对象。 Pod是一个抽象的概念&#xff0c;可以理解为一个或者多个容器化应用的集合。 在一个pod当中运行一个容器是最常用的方式。 在一个pod当中同时运行多个容器&#xff0c;在一个pod当中…

微软最新研究成果:使用GPT-4合成数据来训练AI模型,实现SOTA!

文本嵌入是各项NLP任务的基础&#xff0c;用于将自然语言转换为向量表示。现有的大部分方法通常采用复杂的多阶段训练流程&#xff0c;先在大规模数据上训练&#xff0c;再在小规模标注数据上微调。此过程依赖于手动收集数据制作正负样本对&#xff0c;缺乏任务的多样性和语言多…

王中阳Go赠书活动第一期:《TVM编译器原理与实践》

文章目录 前言TVM编译器的实现过程关于《TVM编译器原理与实践》编辑推荐内容简介作者简介图书目录书中前言/序言《TVM编译器原理与实践》全书速览入手《TVM编译器原理与实践》传送门&#xff1a;结束语参加抽奖 前言 随着人工智能的发展&#xff0c;计算机视觉、自然语言处理和…

算法第4版 第2章排序

综述&#xff1a;5个小节&#xff0c;四种排序应用&#xff0c;初级排序、归并排序、快速排序、优先队列 2.1.初级排序 排序算法模板&#xff0c;less(), exch(), 排序代码在sort()方法中&#xff1b; 选择排序&#xff1a;如升序排列&#xff0c;1.找到数组中最小的元素&am…

2024年R1快开门式压力容器操作证模拟考试题库及R1快开门式压力容器操作理论考试试题

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 2024年R1快开门式压力容器操作证模拟考试题库及R1快开门式压力容器操作理论考试试题是由安全生产模拟考试一点通提供&#xff0c;R1快开门式压力容器操作证模拟考试题库是根据R1快开门式压力容器操作最新版教材&#…

【IPC通信--消息队列】

消息队列&#xff08;也叫做报文队列&#xff09;是一个消息的链表。可以把消息看作一个记录&#xff0c;具有特定的格式以及特定的优先级。对消息队列有写权限的进程可以向消息队列中按照一定的规则添加新消息&#xff1b;对消息队列有读权限的进程则可以从消息队列中读走消息…

优秀案例 | 嘉吉动物营养虚拟人IP“小嘉”, 虚拟动力提供常态化高效率短视频制作工具

在流量见顶的时代 品牌宣传逐渐精细化 塑造一个具备亲和力及创新感的虚拟IP 可以持续扩大品牌影响力 与挖掘品牌更多可能性 「嘉吉动物营养」紧随营销趋势&#xff0c;通过广州虚拟动力「虚拟人运营套装」&#xff0c;将虚拟人IP运营与品牌宣传相结合&#xff0c;带动品牌形…

从音乐“卷”到直播,涨价也救不了腾讯音乐

继6月大规模涨价之后&#xff0c;腾讯音乐娱乐集团&#xff08;下称“腾讯音乐”&#xff0c;01698.HK&#xff09;旗下QQ音乐会员再次涨价。 「不二研究」据腾讯音乐三季报发现&#xff1a;在会员数这一关键指标上&#xff0c;腾讯音乐在三季度的月活跃用户从去年同期的6.20亿…

STM32深入系列02——BootLoader分析与实现

文章目录 1. STM32程序升级方法1.1 ST-Link / J-link下载1.2 ISP&#xff08;In System Programing&#xff09;1.3 IAP&#xff08;In Applicating Programing&#xff09;1.3.1 正常程序运行流程1.3.2 有IAP时程序运行流程 2. STM32 Bootloader实现2.1 方式一&#xff1a;Boo…

开启Android学习之旅-2-架构组件实现数据列表及添加(kotlin)

Android Jetpack 体验-官方codelab 1. 实现功能 使用 Jetpack 架构组件 Room、ViewModel 和 LiveData 设计应用&#xff1b;从sqlite获取、保存、删除数据&#xff1b;sqlite数据预填充功能&#xff1b;使用 RecyclerView 展示数据列表&#xff1b; 2. 使用架构组件 架构组…