使用 QProcess 读取标准输出

Using QProcess to read standard output

在我的 QT 小部件应用程序中,我试图 运行 一个 shell 脚本来打开 C++ 程序并为程序提供输入。该程序启动一个命令提示符,需要用户输入才能启动。程序启动后,程序的输出将通过标准输出重定向到文本文件。我正在尝试使用 QProcess 打开并 运行 这个 shell 脚本,然后读取用于将 C++ 程序的结果打印到文本文件的标准输出。 shell 脚本仅 运行 执行此进程,而不会终止它。这是因为我需要不断地将此输出读入 GUI,因为程序是 运行ning。等到程序完成后再读取此信息是不够的。我对 QT 和 C++ 编程还很陌生。我希望有人可以帮助我实现这一点。

QProcess process;
process.start("/home/pi/Desktop/ShellScripts/RunTutorial3.sh");
QString output =process.readAllStandardOutput();
qDebug() << output;
QString err = process.readAllStandardError();
qDebug() << err;

我已经尝试使用其他读取函数(例如 readline)并尝试将进程作为分离进程启动。我的任何实验都没有成功。是否有可能做我在 QT 中尝试的事情。我只需要程序连续 运行 并让 QT 每隔一段时间读取此输出。

Shell 脚本:

#!/bin/bash
cd
cd Desktop
cd tutorial3App
cd bin
echo "start" | ./tutorial3 

C++ 代码:我需要在标准输出中捕获 meanTOE 值,以便在我的 GUI 中使用。

/ Calculate average time to end of discharge
            double meanToE = std::accumulate(ToESamples.begin(), ToESamples.end(), 0.0)/ToESamples.size();
            file << ": EOL in " << meanToE << " s" << std::endl;

我认为您必须了解 Qt 中的信号和槽。 QProcess 有一个信号 readyReadStandardOutput。所以你必须连接到这个信号,在你的插槽中你应该使用 QProcess 函数 readAllStandardOutput。换句话说,当你的 shell 程序输出一些东西时,你可以在你的插槽中捕获它并转储它或任何你想要的东西。

检查这个问题的答案。可能对你有帮助。

正如我在评论中所说,一个主要问题是,当您 运行 tutorial3 该过程被分离时,您无法获得输出。所以,我建议直接执行,QProcess可能是一个局部变量,打印空文本后消除,一个可能的解决方案是创建一个指针。另一个改进是使用 readyReadStandardOutput 和 readyReadStandardError 信号,因为印象不是自动的。

QProcess *process = new QProcess(this);

connect(process, &QProcess::readyReadStandardOutput, [process, this](){
    QString output =process->readAllStandardOutput();
    qDebug() << "output: "<< output;
});

connect(process, &QProcess::readyReadStandardError, [process](){
    QString err = process->readAllStandardError();
    qDebug() << "error: "<<err;
});

process->setWorkingDirectory("/home/pi/Desktop/tutorial3App/bin/")
process->start("tutorial3", QStringList() << "start");