2

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.

Sphics
  • 88
  • 1
  • 9
  • What does it mean "does not seem to work"? Do you get the empty output? I would check the resoure file existence first with `QFile::exists(":/someScript.sh")` – paceholder Dec 21 '16 at 10:18
  • The script executes (I can see that it does from other sources), but I get empty output. – Sphics Dec 21 '16 at 10:24

2 Answers2

6

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 ♥

zakaria chahboun
  • 481
  • 6
  • 13
1

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.

Benjamin T
  • 8,120
  • 20
  • 37
  • The script runs, as I can see its results outside of my program. I just don't get the console output that I would when running it externally. – Sphics Dec 21 '16 at 10:28
  • Check `QProcess:error()` and `QProcess::errorString()`. I've just test on ubuntu with Qt 5.6 and I have: QProcess::FailedToStart and "No such file or directory". Also I have absolutely no sign of the script ever being executed. – Benjamin T Dec 21 '16 at 11:01