【发布时间】:2019-04-25 23:24:43
【问题描述】:
我想通过 QProcess 调用可执行文件。可执行文件的路径可以包含空格。因此,我在可执行文件的路径周围加上引号。
但是,这仅在我不添加任何参数时才有效。
下面的代码重现了这个问题:
#include <QCoreApplication>
#include <QProcess>
#include <QDebug>
#include <QDir>
int main(int argc, char *argv[])
{
int i = 0; // no whitespace, no argument -> works
// int i = 1; // whitespace with quotation, no arguments -> works
// int i = 2; // no whitespace, arguments -> works
// int i = 3; // whitespace with quotation, arguments -> works not
QCoreApplication a(argc, argv);
QProcess *process = new QProcess();
QString pathToFile;
QString absolutePathToProgram;
pathToFile = "/home/user/tmp/file.xml";
if (i == 0){
absolutePathToProgram = "/home/user/tmp/executable";
}else if(i == 1){
absolutePathToProgram = "/home/user/tmp whitespace/executable";
absolutePathToProgram = "\"" + absolutePathToProgram + "\"";
}else if(i == 2){
absolutePathToProgram = "/home/user/tmp/executable";
}else if(i == 3){
absolutePathToProgram = "/home/user/tmp whitespace/executable";
absolutePathToProgram = "\"" + absolutePathToProgram + "\"";
}
QStringList arguments;
arguments << pathToFile;
if (i==0 || i==1){
process->start(absolutePathToProgram);
}else{
process->start(absolutePathToProgram,arguments);
}
process->waitForFinished();
QString output(process->readAllStandardOutput());
qDebug() << output;
return a.exec();
}
我添加了4个案例:
-
i == 0:可执行文件的路径不包含空格,我们不传递参数。这行得通 -
i == 1:可执行文件的路径确实包含空格,我们不传递参数。这行得通 -
i == 2:可执行文件的路径不包含空格,我们确实传递了参数。这行得通 -
i == 3:可执行文件的路径确实包含空格,我们确实传递了参数。这不起作用
为什么 case i == 3 不起作用?
我使用 Ubuntu 作为操作系统。
奖励:
我还需要让它在 Windows 上运行。通常,在 Windows 上,我启动程序:
process->start("cmd.exe", QStringList() << "/c" << absolutePathToProgram << pathToFile);
我没有时间在 Windows 上测试它,但如果有人发布答案并且知道如何在 Windows 上创建解决方案,请告诉我。
【问题讨论】:
-
Mmm... 处理它正在为我执行(Windows 10 + Visual Studio 15.9.2 + Qt 5.10.0)。究竟什么是“不工作”?进程未启动?没有读取标准输出?
-
感谢测试。我还没有用windows测试它。在我的 Ubuntu 上它不工作。明天我会添加我的 gcc qt 版本。我的问题是,该过程没有启动。您究竟是如何使用 windows 开始您的流程的(您可以发布您的代码行
process->start())吗? -
我修改了您的示例,第 29 行:
absolutePathToProgram = "C:\\Program Files (x86)\\Notepad++\\notepad++.exe";和 34:arguments << "c:\\readme.md" << "-loadingTime";。其余的都是你的例子。
标签: c++ qt process path arguments