简体   繁体   English

运行资源文件时重定向QProcess的输出

[英]Redirecting the output of QProcess when running a resource file

fairly new to Qt. 对Qt来说还很新。

I'm using QProcess to run an external shell script and redirecting the output to a textBrowser on my GUI. 我正在使用QProcess运行外部Shell脚本,并将输出重定向到GUI上的textBrowser。 Code: 码:

In mainwindow.h: 在mainwindow.h中:

private:
   QProcess *myProcess;

and mainwindow.cpp: 和mainwindow.cpp:

void MainWindow::onButtonPressed(){
   myProcess = new QProcess(this);
   myProcess->connect(myProcess, SIGNAL(readyRead()), this, SLOT(textAppend()));
   myProcess->start("./someScript.sh", arguments);
}

void MainWindow::textAppend(){
   ui->textBrowser->append(myProcess->readAll());
}

This works perfectly to run an external script. 这非常适合运行外部脚本。 My question is how to apply the same process with the script included as a resource file. 我的问题是如何对包含在资源文件中的脚本应用相同的过程。 I've tried simply replacing "./someScript.sh" with the resource version ":/someScript.sh" but it does not seem to work. 我尝试用资源版本":/someScript.sh"简单地替换"./someScript.sh" ,但是它似乎不起作用。 The resource script runs perfectly, but the console output disappears. 资源脚本运行完美,但控制台输出消失。

For this reason, there is something called " QTemporaryFile " class. 因此,有一个名为“ QTemporaryFile ”的类。

Because you need to call a file that already exists in your system - ok! 因为您需要调用系统中已经存在的文件-好的!

let's take this example : 让我们举个例子:

using QProcess we need to run a python file from resource 使用QProcess我们需要从资源中运行一个python文件

//[1] Get Python File From Resource
QFile RsFile(":/send.py");
//[2] Create a Temporary File
QTemporaryFile *NewTempFile = QTemporaryFile::createNativeFile(RsFile);
//[3] Get The Path of Temporary File
QStringList arg;
arg << NewTempFile->fileName();
//[4] Call Process
QProcess *myProcess = new QProcess(this);
myProcess->start("python", arg);
//[5] When You Finish, remove the temporary file
NewTempFile->remove();

Note : on windows, the Temporary File stored in %TEMP% directory 注意:在Windows上,临时文件存储在%TEMP%目录中

and for more informations you can visit Qt Documentation - QTemporaryFile Class 有关更多信息,请访问Qt文档-QTemporaryFile类

Good Luck ♥ 祝你好运♥

I does not work because when you run myProcess->start(":/someScript.sh", arguments); 我无法工作,因为当您运行myProcess->start(":/someScript.sh", arguments); you ask your system to run :/someScript.sh which does not exist for your system. 您要求系统运行:/someScript.sh ,这对于您的系统不存在。

A quick solution would be to copy the script to a temporary folder and run it from there. 一种快速的解决方案是将脚本复制到一个临时文件夹,然后从那里运行它。

QFile::copy(":/someScript.sh", pathToTmpFile);
myProcess->start(pathToTmpFile, arguments);

I would also suggest you make use of QTemporaryFile to get a unique temporary file name. 我还建议您使用QTemporaryFile获得唯一的临时文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM