Redirecting the output of QProcess when running a resource file

1.2k views Asked by At

fairly new to Qt.

I'm using QProcess to run an external shell script and redirecting the output to a textBrowser on my GUI. Code:

In mainwindow.h:

private:
   QProcess *myProcess;

and 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. The resource script runs perfectly, but the console output disappears.

2

There are 2 answers

1
zakaria chahboun On BEST ANSWER

For this reason, there is something called "QTemporaryFile" class.

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

//[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

and for more informations you can visit Qt Documentation - QTemporaryFile Class

Good Luck ♥

2
Benjamin T On

I does not work because when you run myProcess->start(":/someScript.sh", arguments); you ask your system to run :/someScript.sh which does not exist for your system.

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.