【问题标题】:QProcess and command line "/c" argumentQProcess 和命令行“/c”参数
【发布时间】:2012-10-07 13:38:14
【问题描述】:

我对 QProcess 有一个非常奇怪的问题,而且它的行为很奇怪。

我最后想得到的是这样的(这是 Windows 7 中的 cmd.exe)

C:\path_to_somewhere>cmd /c "C:\Program Files\path_to_dir\executable"

(cmd是为了兼容QProcess的show)

为了做类似的事情,我创建了这个:

QProcess proc;
QString command;
QStringList attributes;

command = "c:\\windows\\system32\\cmd.exe";
QStringList << QString("/c \"C:\\Program Files\\path_to-dir\\executable"");
proc.start(command, attributes);

我得到的错误输出是:

Name '\"c:\Program Files\Quantum GIS Wroclaw\bin\gdalwarp.exe\"' is not recognized as
internat or external command, executable or batch file.

(它是我从波兰语翻译过来的,所以英文可能有点不同)。

似乎 \ 字符没有在字符串中转义,将 \" 作为命令中的字符。我做错了什么?

我试过了

proces.start(QString) 

具有三重\“\”\”的功能,它也不起作用。我想这个问题的解决方案必须非常简单,以至于我没有考虑它。

【问题讨论】:

    标签: escaping qstring qprocess


    【解决方案1】:

    好的,我不知道这是否是 Qt 错误,但在有关 void QProcess::start(QString, QStringList, OpenMode) 的文档中是这样说的:

    Windows:包含空格的参数用引号括起来。

    似乎这不是真的,因为我的程序使用带空格的路径并且 cmd shell 在那里中断。

    但是,我发现了为仅接受一个字符串参数的系统设计的函数(就像 Windows 一样)。

    我是QProcess::setNativeArguments(QString)

    接受一个 QString 作为参数,专为 Windows 和 Symbian 创建。

    毕竟,如果有人在将 Windows(或 Symbian)中的参数传递给系统时遇到问题,他应该尝试setNativeArguments(QString)

    【讨论】:

      【解决方案2】:

      正如您已经注意到的,Qt 将包含空格的参数用引号括起来,这意味着QProcess 发出的实际命令看起来像这样(不确定内部引号):

      c:\windows\system32\cmd.exe "/c \"C:\Program Files\path_to_dir\executable\""
      

      这不是你想要的:整个字符串被传递给cmd,包括/c。由于/c 和路径是两个参数,您应该将它们分别传递给QProcess,而不用担心空格,因为它们会被自动处理:

      QString command = "cmd.exe";
      QStringList arguments = 
          QStringList() << "/c" << "C:\\Program Files\\path_to_dir\\executable";
      // note there are two arguments now, and the path is not enclosed in quotes
      proc.start(command, arguments);
      

      【讨论】: