如何使用 QProcess 中的 bash 命令'which'

How to use the bash command 'which' from QProcess

本文关键字:which 命令 bash 何使用 QProcess 中的      更新时间:2023-10-16

我是一名使用Qt的学生程序员,我似乎在使用QProcess启动bash命令"which"以尝试收集应用程序的安装图时遇到了问题。我有以下代码,我真的不知道我可能缺少什么。我已经参考了QProcess文档,但仍然无法弄清楚出了什么问题。

每次运行此代码时,都不会在指定的目录中创建文件。如果没有构建的文件,应用程序将无法继续。

//datatypes
QProcess *findFiles = new QProcess();
QStringList arguments;
QStringList InstallationList;
QString program = "/bin/bash";
QString currentUsersHomeDirectory = QDir::homePath();
QString tmpScriptLocation = currentUsersHomeDirectory;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
//generate file with list of files found
tmpScriptLocation += ".whichBAScriptOutput";
arguments << QString(QString("which -a certainFile >> ") += tmpScriptLocation);
findFiles->setProcessEnvironment(env);
findFiles->start(program,arguments);
findFiles->waitForFinished();
位于

/usr/bin/ 上,因此请尝试更改路径。

编辑:您需要将QProcess的信号readyReadStandardOutput()连接到您的插槽。实际上,如果您查看QProcessQIODevice继承的文档。这意味着您可以执行以下操作:

while(canReadLine()){
   string line = readLine();
   ...
}

如果您已经用Qt编写了客户端-服务器应用程序,我相信您重新协调了伪代码。

正如你所说,你想执行which,但你正在用手写脚本来bash。有一种更简单的方法可以按顺序执行此操作:

//preparing the job, 
QProcess process;
QString processName = "which"; //or absoute path if not in path
QStringList arguments = QStringList() << "-a" 
                                      << "certainFile.txt";
// process.setWorkingDirectory() //if you want it to execute in a specific directory
//start the process                                  
process.start(processName, arguments ); 
//sit back and wait                                     
process.waitForStarted(); //blocking, return bool
process.waitForFinished(); //blocking, return bool                                      
if(process.exitCode() != 0){
  //Something went wrong
}
//return a byte array containing what the command "which" print in console
QByteArray processOutput = process.readAll();