I have a python Script. I would like to run the python script in qt with passing an argument.
For Example, python python_script.py 10 This script would return the factorial of 10.
I want to run this command line in Qt. I've tried this way. It works. I would want to understand the working of the program. Here is the code, I have tried executing. Better Solutions would be appreciated.
'''
QString path = "D:\Task_3\";
QString command("python");
QStringList params = QStringList()<< "python_script.py";
QProcess *process = new QProcess();
process->startDetached(command, params, path);
process->waitForFinished();
process->close();
'''
There are several issues in your code.
QProcess process;
process.start("python", {"python_script.py"});
process.waitForFinished();
If you want to wait for the command to finish, you cannot start it detached. You should use the start method instead for that. For example:
Backslashes may need to be escaped by backslashes, although if you switch to the start method as above, this may not even be relevant.
In general, in cross-platform Qt applications, you ought to avoid hard-coding operating system specific paths, like a specific Windows path. You ought to offer a cross-platform solution, like running it from the script directory or some sort of file selection QDialog to let the user to select the path for running. This depends on the exact use case.
Slight nitpick, but you either do not need a heap instance (pointer) for the QProcess
instance or you ought to parent it so that it does not leak memory.