Reputation: 69
I am trying to run a script in parallel to my Qt program and am having trouble starting it as a separate process. Check out my attempts below and let me know what you see wrong.
The first attempt was just a system call:
system("python3 startprocess.py");
This works but it also stops the program while running it.
I then followed this guy https://forum.qt.io/topic/92205/writing-commands-to-linux-bash with no success. No errors, just no start of my script.
I am trying this after I saw the documentation and have the below code.
QProcess process;
process.start("python3 startprocess.py");
process.waitForStarted();
I am just wanting to start this script and have it run at the same time as my C++ code. Perhaps I am using the QProcess wrong?
UPDATE: It was a lot easier to use QThreading and the original system call.
Upvotes: 0
Views: 276
Reputation: 490
I think the issue is that the QProcess
doesn't have the file path and fails to find and start it! I suggest first to use the full file path! Also check the QProcess::setWorkingDirectory and QProcess::setProcessEnvironment that are useful to handle this case!
In order to prevent the QProcess
to be killed while running and without freezing the GUI, you need to define it as a pointer, then connect the QProcess::finished
event; in the slot, you can check the exit code and delete the sender using QObject::deleteLater
method. Check both the Qt example and the QProcess::finished.
Try this code:
auto process = new QProcess(this);
connect(process, QOverload<int,QProcess::ExitStatus>::of(&QProcess::finished),
[this](int exitCode, QProcess::ExitStatus exitStatus)
{
if (exitStatus == QProcess::ExitStatus::CrashExit
|| exitCode != 0) {
// Process error!
} else {
// Process OK!
}
});
process->setWorkingDirectory("startprocess.py folder location");
process->start("python3 startprocess.py");
if (!process->waitForStarted(-1)) {
// Failed to start process
delete process;
}
Upvotes: 1