qt-C++笔记之QProcess

2024-01-08 12:44
文章标签 c++ qt 笔记 qprocess

本文主要是介绍qt-C++笔记之QProcess,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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=$1if [ -z "$DIR" ]; thenecho "Usage: $0 <directory>"exit 1
fils $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 secondsreturn 1;if (!process.waitForFinished()) // Default timeout is 30 secondsreturn 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.

这篇关于qt-C++笔记之QProcess的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/583497

相关文章

C++ Primer 标准库vector示例详解

《C++Primer标准库vector示例详解》该文章主要介绍了C++标准库中的vector类型,包括其定义、初始化、成员函数以及常见操作,文章详细解释了如何使用vector来存储和操作对象集合,... 目录3.3标准库Vector定义和初始化vector对象通列表初始化vector对象创建指定数量的元素值

Qt实现发送HTTP请求的示例详解

《Qt实现发送HTTP请求的示例详解》这篇文章主要为大家详细介绍了如何通过Qt实现发送HTTP请求,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、添加network模块2、包含改头文件3、创建网络访问管理器4、创建接口5、创建网络请求对象6、创建一个回复对

C++实现回文串判断的两种高效方法

《C++实现回文串判断的两种高效方法》文章介绍了两种判断回文串的方法:解法一通过创建新字符串来处理,解法二在原字符串上直接筛选判断,两种方法都使用了双指针法,文中通过代码示例讲解的非常详细,需要的朋友... 目录一、问题描述示例二、解法一:将字母数字连接到新的 string思路代码实现代码解释复杂度分析三、

C++一个数组赋值给另一个数组方式

《C++一个数组赋值给另一个数组方式》文章介绍了三种在C++中将一个数组赋值给另一个数组的方法:使用循环逐个元素赋值、使用标准库函数std::copy或std::memcpy以及使用标准库容器,每种方... 目录C++一个数组赋值给另一个数组循环遍历赋值使用标准库中的函数 std::copy 或 std::

Qt 中集成mqtt协议的使用方法

《Qt中集成mqtt协议的使用方法》文章介绍了如何在工程中引入qmqtt库,并通过声明一个单例类来暴露订阅到的主题数据,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一,引入qmqtt 库二,使用一,引入qmqtt 库我是将整个头文件/源文件都添加到了工程中进行编译,这样 跨平台

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

c++中std::placeholders的使用方法

《c++中std::placeholders的使用方法》std::placeholders是C++标准库中的一个工具,用于在函数对象绑定时创建占位符,本文就来详细的介绍一下,具有一定的参考价值,感兴... 目录1. 基本概念2. 使用场景3. 示例示例 1:部分参数绑定示例 2:参数重排序4. 注意事项5.