[英]I am trying to run a python script in qt creator by calling command prompt. Can anybody help me with this?
I have a python Script.我有一个 python 脚本。 I would like to run the python script in qt with passing an argument.
我想通过传递参数在 qt 中运行 python 脚本。
For Example, python python_script.py 10 This script would return the factorial of 10.例如,python python_script.py 10 此脚本将返回 10 的阶乘。
I want to run this command line in Qt.我想在 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.
为此,您应该使用start 方法。 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.反斜杠可能需要用反斜杠转义,尽管如果您切换到上面的 start 方法,这甚至可能无关紧要。
In general, in cross-platform Qt applications, you ought to avoid hard-coding operating system specific paths, like a specific Windows path.通常,在跨平台 Qt 应用程序中,您应该避免硬编码操作系统特定路径,例如特定 Windows 路径。 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.
你应该提供一个跨平台的解决方案,比如从脚本目录运行它或者某种文件选择QDialog让用户以select的路径运行。 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.有点挑剔,但是您要么不需要
QProcess
实例的堆实例(指针),要么应该将其作为父对象,以免它泄漏 memory。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.