gpt4 book ai didi

c++ - Qt: QProcess调用终端+脚本

转载 作者:搜寻专家 更新时间:2023-10-31 00:36:50 25 4
gpt4 key购买 nike

我在使用 QProcess 时遇到了真正的麻烦,我查看了几个使用它的位置,但每次我使用它时,我的程序都会卡住,或者它只是不执行我想要它执行的操作。

我想从我的 GUI 应用程序中执行以下操作:

将目录更改为/Users/Tim/etc 等。我需要从那里调用 gnuplot 并将脚本加载到其中。

我通常会在终端窗口中执行以下操作:

 > cd /Users/Tim/...        
> /opt/local/bin/gnuplot barchartscript.txt

目前我正在使用系统调用来执行此操作,并且可行,但每个人都建议使用 QProcess,因此我想这样做。

我的代码现在使用 QProcess 时的样子:

    QObject *parent;
QProcess *process = new QProcess(parent);
QString commands;
QString changed = "cd /Users/Tim/etcetc";
commands = (changed + "&& /opt/local/bin/gnuplot scatterplotscriptwithout.txt").c_str();

process->start(commands);

谁能告诉我这是怎么回事?或者在一个进程中执行多个命令的正确方法?

最佳答案

此代码段可能有用(未经测试)。引用QProcess有关每种方法的详细信息的文档。

process->setWorkingDirectory("/Users/Tim/etcetc");
process->setArguments(QStringList() << "scatterplotscriptwithout.txt");
process->start("/opt/local/bin/gnuplot");

编辑

另一个在你的程序中看起来错误的事情是你作为父级给你的 QProcess 实例的未定义​​指针。设置父级以利用自动删除子级是很有用的。在这种情况下,只需注意自己删除 QProcess 实例即可。

编辑 2(错误处理)

QProcess *process = new QProcess;
connect(process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(handleError(QProcess::ProcessError)));

然后定义一个合适的slot(这里是handleError)

void MyClass::handleError(QProcess::ProcessError error) {
switch(error) {
case QProcess::FailedToStart:
qDebug() << "Failed to start, may be due to insufficient permissions";
break;
case QProcess::Crashed:
qDebug() << "Program crashed.";
break;
//debug each case..
}
}

参见 here有关所有枚举值的详细信息。

如果您的 QProcess 正确结束但未产生预期的输出,您可以查看进程的退出代码并引用 gnuplot 手册页以获取信息。

关于c++ - Qt: QProcess调用终端+脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20841116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com