Home > Blockchain >  I am trying to run a python script in qt creator by calling command prompt. Can anybody help me with
I am trying to run a python script in qt creator by calling command prompt. Can anybody help me with

Time:08-10

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();

'''

CodePudding user response:

There are several issues in your code.

QProcess process;
process.start("python", {"python_script.py"});
process.waitForFinished();
  1. 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:

  2. Backslashes may need to be escaped by backslashes, although if you switch to the start method as above, this may not even be relevant.

  3. 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.

  4. 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.

  • Related