bool zip() { //! [0] QProcess gzip; gzip.start("gzip", QStringList() << "-c"); if (!gzip.waitForStarted()) return false; gzip.write("Qt rocks!"); gzip.closeWriteChannel(); if (!gzip.waitForFinished()) return false; QByteArray result = gzip.readAll(); //! [0] gzip.start("gzip", QStringList() << "-d" << "-c"); gzip.write(result); gzip.closeWriteChannel(); if (!gzip.waitForFinished()) return false; qDebug("Result: %s", gzip.readAll().data()); return true; }
void DiagnosticsDialog::showDetails() { QProgressDialog box( tr( "Generating diagnostics\n\nPlease wait..." ), QString(), 0, 0, qApp->activeWindow() ); box.setWindowTitle( windowTitle() ); box.setWindowFlags( (box.windowFlags() | Qt::CustomizeWindowHint) & ~Qt::WindowCloseButtonHint ); if( QProgressBar *bar = box.findChild<QProgressBar*>() ) bar->setVisible( false ); box.open(); QApplication::processEvents(); QString ret; QProcess p; p.start( "opensc-tool", QStringList() << "-la" ); p.waitForFinished(); QString cmd = QString::fromUtf8( p.readAll() ); if ( !cmd.isEmpty() ) ret += "<b>" + tr("OpenSC tool:") + "</b><br/> " + cmd.replace( "\n", "<br />" ) + "<br />"; QApplication::processEvents(); p.start( "pkcs11-tool", QStringList() << "-T" ); p.waitForFinished(); cmd = QString::fromUtf8( p.readAll() ); if ( !cmd.isEmpty() ) ret += "<b>" + tr("PKCS11 tool:") + "</b><br/> " + cmd.replace( "\n", "<br />" ) + "<br />"; if ( !ret.isEmpty() ) diagnosticsText->append( ret ); }
void tst_QUdpSocket::outOfProcessUnconnectedClientServerTest() { #if defined(Q_OS_WINCE) QSKIP("This test depends on reading data from QProcess (not supported on Qt/WinCE.", SkipAll); #endif #if defined(QT_NO_PROCESS) QSKIP("Qt was compiled with QT_NO_PROCESS", SkipAll); #else QProcess serverProcess; serverProcess.start(QLatin1String("clientserver/clientserver server 1 1"), QIODevice::ReadWrite | QIODevice::Text); // Wait until the server has started and reports success. while (!serverProcess.canReadLine()) QVERIFY(serverProcess.waitForReadyRead(3000)); QByteArray serverGreeting = serverProcess.readLine(); QVERIFY(serverGreeting != QByteArray("XXX\n")); int serverPort = serverGreeting.trimmed().toInt(); QVERIFY(serverPort > 0 && serverPort < 65536); QProcess clientProcess; clientProcess.start(QString::fromLatin1("clientserver/clientserver unconnectedclient %1 %2") .arg(QLatin1String("127.0.0.1")).arg(serverPort), QIODevice::ReadWrite | QIODevice::Text); // Wait until the server has started and reports success. while (!clientProcess.canReadLine()) QVERIFY(clientProcess.waitForReadyRead(3000)); QByteArray clientGreeting = clientProcess.readLine(); QCOMPARE(clientGreeting, QByteArray("ok\n")); // Let the client and server talk for 3 seconds QTest::qWait(3000); QStringList serverData = QString::fromLocal8Bit(serverProcess.readAll()).split("\n"); QStringList clientData = QString::fromLocal8Bit(clientProcess.readAll()).split("\n"); QVERIFY(serverData.size() > 5); QVERIFY(clientData.size() > 5); for (int i = 0; i < clientData.size() / 2; ++i) { QCOMPARE(clientData.at(i * 2), QString("readData()")); QCOMPARE(serverData.at(i * 3), QString("readData()")); QString cdata = clientData.at(i * 2 + 1); QString sdata = serverData.at(i * 3 + 1); QVERIFY(cdata.startsWith(QLatin1String("got "))); QCOMPARE(cdata.mid(4).trimmed().toInt(), sdata.mid(4).trimmed().toInt() * 2); QVERIFY(serverData.at(i * 3 + 2).startsWith(QLatin1String("sending "))); QCOMPARE(serverData.at(i * 3 + 2).trimmed().mid(8).toInt(), sdata.mid(4).trimmed().toInt() * 2); } clientProcess.kill(); QVERIFY(clientProcess.waitForFinished()); serverProcess.kill(); QVERIFY(serverProcess.waitForFinished()); #endif }
//the code is sent to a compiler and ran afterwards. The output is displayed in the terminal. void StudentWindow::on_compileButton_clicked() { QFile Compile("temp.cs"); Compile.open(QIODevice::WriteOnly); QTextStream out(&Compile); out << (ui->opdrachtCode->toPlainText()); out.flush(); //wait until write is done. Compile.close(); QString CompilerLocation="C:/Windows/Microsoft.NET/Framework/v4.0.30319/csc.exe"; //TODO: allow the user to select a compiler. QStringList CompilerArgs; CompilerArgs.append("temp.cs"); //Tested with the first example at https://msdn.microsoft.com/en-us/library/aa288463%28v=vs.71%29.aspx?f=255&MSPPError=-2147217396 QProcess *Compiler = new QProcess(); Compiler->start(CompilerLocation, CompilerArgs); Compiler->waitForFinished(5000); //give the compiler at most 5 seconds (for now) if(Compiler->exitStatus()==0&&Compiler->exitCode()==0){ QProcess *TestProgram = new QProcess(); TestProgram->start("./temp.exe"); TestProgram->waitForFinished(5000); //give the program at most 5 seconds (for now) QByteArray result=TestProgram->readAll(); ui->opdrachtTerminal->setText(result); } else { QByteArray compileError=Compiler->readAll(); ui->opdrachtTerminal->setText(compileError); } }
int Battery::currentLevel() { #if defined Q_OS_WIN GetSystemPowerStatus (&power); return static_cast<int> (power.BatteryLifePercent); #endif #if defined Q_OS_MAC QByteArray data; QProcess process; process.start ("pmset -g batt"); while (process.waitForReadyRead()) data.append (process.readAll()); /* Parse the digits of the percentage */ int h = data.at (data.indexOf ("%") - 3) - '0'; // Hundreds int t = data.at (data.indexOf ("%") - 2) - '0'; // Tens int u = data.at (data.indexOf ("%") - 1) - '0'; // Units /* Process data is invalid or we do not know how to read */ if (h < 0) h = 0; if (t < 0) t = 0; if (u < 0) u = 0; return (h * 100) + (t * 10) + u; #endif #if defined Q_OS_LINUX QByteArray data; QProcess process; process.start ("bash -c \"upower -i $(upower -e | grep 'BAT') | " "grep -E 'state|to\\ full|percentage'\""); while (process.waitForReadyRead()) data.append (process.readAll()); /* Parse the digits of the percentage */ int h = data.at (data.indexOf ("%") - 3) - '0'; // Hundreds int t = data.at (data.indexOf ("%") - 2) - '0'; // Tens int u = data.at (data.indexOf ("%") - 1) - '0'; // Units /* Process data is invalid or we do not know how to read */ if (h < 0) h = 0; if (t < 0) t = 0; if (u < 0) u = 0; return (h * 100) + (t * 10) + u; #endif }
void tst_QCommandLineParser::testHelpOption() { #ifdef QT_NO_PROCESS QSKIP("This test requires QProcess support"); #else #ifdef Q_OS_WINCE QSKIP("Reading and writing to a process is not supported on Qt/CE"); #endif #if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_NO_SDK) QSKIP("Deploying executable applications to file system on Android not supported."); #endif QFETCH(QCommandLineParser::SingleDashWordOptionMode, parsingMode); QFETCH(QString, expectedHelpOutput); QCoreApplication app(empty_argc, empty_argv); QProcess process; process.start("testhelper/qcommandlineparser_test_helper", QStringList() << QString::number(parsingMode) << "--help"); QVERIFY(process.waitForFinished(5000)); QCOMPARE(process.exitStatus(), QProcess::NormalExit); QString output = process.readAll(); #ifdef Q_OS_WIN output.replace(QStringLiteral("\r\n"), QStringLiteral("\n")); #endif QCOMPARE(output.split('\n'), expectedHelpOutput.split('\n')); // easier to debug than the next line, on failure QCOMPARE(output, expectedHelpOutput); process.start("testhelper/qcommandlineparser_test_helper", QStringList() << "0" << "resize" << "--help"); QVERIFY(process.waitForFinished(5000)); QCOMPARE(process.exitStatus(), QProcess::NormalExit); output = process.readAll(); #ifdef Q_OS_WIN output.replace(QStringLiteral("\r\n"), QStringLiteral("\n")); #endif QByteArray expectedResizeHelp = QByteArrayLiteral( "Usage: testhelper/qcommandlineparser_test_helper [options] resize [resize_options]\n" "Test helper\n" "\n") + expectedOptionsHelp + " --size <size> New size.\n" "\n" "Arguments:\n" " resize Resize the object to a new size.\n"; #ifdef Q_OS_WIN expectedResizeHelp.replace(" -h, --help Displays this help.\n", " -?, -h, --help Displays this help.\n"); expectedResizeHelp.replace("testhelper/", "testhelper\\"); #endif QCOMPARE(output, QString(expectedResizeHelp)); #endif // !QT_NO_PROCESS }
/** Runs the specified command (should be ffmpeg) and allows for progress feedback. * * @param[in] strCmd A string containing the command to execute and * all of its arguments * @param[out] progress A function that takes one float argument * (the percentage of the ffmpeg operation complete) and * may display the output to the user in any way it * sees fit. * * executeFFMpeg does not allow for writing direct input, the only * input through the "-i" argument to specify input files on the disk. * * @return Returns Status::OK if everything went well, and Status::FAIL * and error is detected (usually a non-zero exit code for ffmpeg). */ Status MovieExporter::executeFFMpeg(QString strCmd, std::function<void(float)> progress) { qDebug() << strCmd; QProcess ffmpeg; ffmpeg.setReadChannel(QProcess::StandardOutput); // FFmpeg writes to stderr only for some reason, so we just read both channels together ffmpeg.setProcessChannelMode(QProcess::MergedChannels); ffmpeg.start(strCmd); if (ffmpeg.waitForStarted() == true) { while(ffmpeg.state() == QProcess::Running) { if(!ffmpeg.waitForReadyRead()) break; QString output(ffmpeg.readAll()); QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); for (const QString& s : sList) { qDebug() << "[stdout]" << s; } if(output.startsWith("frame=")) { QString frame = output.mid(6, output.indexOf(' ')); progress(frame.toInt() / static_cast<float>(mDesc.endFrame - mDesc.startFrame)); } } QString output(ffmpeg.readAll()); QStringList sList = output.split(QRegExp("[\r\n]"), QString::SkipEmptyParts); for (const QString& s : sList) { qDebug() << "[ffmpeg]" << s; } if(ffmpeg.exitStatus() != QProcess::NormalExit) { qDebug() << "ERROR: FFmpeg crashed"; return Status::FAIL; } } else { qDebug() << "ERROR: Could not execute FFmpeg."; return Status::FAIL; } return Status::OK; }
/* * We need this to search for the SH process pid (which spaws yaourt) */ void ProcessWrapper::onSingleShot() { QProcess proc; QProcess pAux; QString saux; proc.start("ps -o pid -C sh"); proc.waitForFinished(-1); QString out = proc.readAll(); proc.close(); QStringList list = out.split("\n", QString::SkipEmptyParts); QStringList slist; for (int c=1; c<list.count(); c++) { int candidatePid = list.at(c).trimmed().toInt(); if (candidatePid < m_pidTerminal) continue; QString cmd = QString("ps --ppid %1").arg(candidatePid); proc.start(cmd); proc.waitForFinished(-1); QString out = proc.readAll(); if (out.contains("yaourt", Qt::CaseInsensitive)) { pAux.start("ps -o pid -C yaourt"); pAux.waitForFinished(-1); saux = pAux.readAll(); slist = saux.split("\n", QString::SkipEmptyParts); for (int d=1; d<slist.count(); d++) { int candidatePid2 = slist.at(d).trimmed().toInt(); if (candidatePid < candidatePid2) { m_pidSH = candidatePid; m_pidYaourt = candidatePid2; m_timer->start(); return; } } } } emit finishedTerminal(0, QProcess::NormalExit); }
QString getGSLinuxPath( QString apps ) { QStringList potential_paths; potential_paths.append("/usr/local/bin"); potential_paths.append("/sw/bin"); /* to use on mac as same */ potential_paths.append("/opt/bin"); QProcess *process = new QProcess(NULL); process->setReadChannelMode(QProcess::MergedChannels); QStringList env = process->systemEnvironment(); env.replaceInStrings(QRegExp("^PATH=(.*)", Qt::CaseInsensitive), "PATH=\\1;"+potential_paths.join(";")); process->setEnvironment(env); process->start( QString("which") , QStringList() << apps , QIODevice::ReadOnly ); if (!process->waitForFinished()) { return QString(); } else { QString finder = process->readAll().trimmed(); if (finder.endsWith(apps,Qt::CaseInsensitive)) { ///////////// qDebug() << "### finder " << finder; return finder; } else { return QString(); } } }
QString MainWindow::TranslateToEnglish(QString LatinWordToTranslate) { QString stringResultFromWhitakersWords; if (LatinWordToTranslate.count() > 0) { QString command = "words"; command += " "; command += LatinWordToTranslate; QProcess whitakersWords; whitakersWords.setReadChannel(QProcess::StandardOutput); whitakersWords.start(command); while (whitakersWords.waitForFinished()) {}; QByteArray resultFromWhitakersWords; resultFromWhitakersWords.append(whitakersWords.readAll()); stringResultFromWhitakersWords = resultFromWhitakersWords.data(); QStringList noLines = stringResultFromWhitakersWords.split('\n'); noLines.removeAt(0); noLines.removeLast(); noLines.removeLast(); stringResultFromWhitakersWords.clear(); stringResultFromWhitakersWords = noLines.join('\n'); } return stringResultFromWhitakersWords; }
QString AsemanDesktopTools::getOpenFileName(QWindow *window, const QString & title, const QString &filter, const QString &startPath) { #ifdef DESKTOP_DEVICE const int dsession = desktopSession(); switch( dsession ) { case AsemanDesktopTools::Kde: if( QFileInfo::exists("/usr/bin/kdialog") ) { QStringList args = QStringList()<< "--title" << title << "--getopenfilename" << startPath << filter; if( window ) args << "--attach" << QString::number(window->winId()); QProcess process; QEventLoop loop; connect(&process, SIGNAL(finished(int)), &loop, SLOT(quit()), Qt::QueuedConnection ); process.start("/usr/bin/kdialog", args ); loop.exec(QEventLoop::ExcludeUserInputEvents); if( process.exitStatus() == QProcess::NormalExit ) return QString(process.readAll()).remove("\n"); else return QFileDialog::getOpenFileName(0, title, startPath, filter); } else return QFileDialog::getOpenFileName(0, title, startPath, filter);
QString FoxGroundDocument::execlocal(const QString cmd, const QStringList args) { QString debughere = cmd; int success = -1; debughere.append(" "); debughere.append(args.join(" ")); //// console(QString("Fox:execlocal: %1").arg(debughere)); QString rec; QProcess *process = new QProcess(NULL); process->setReadChannelMode(QProcess::MergedChannels); process->start(cmd, args, QIODevice::ReadOnly); //// waitForFinished default int msecs = 30000 ok if (!process->waitForFinished(80000)) { success = -1; } else { success = 1; rec = process->readAll(); } if (success == 1) { process->close(); return rec; } else { process->close(); return QString("ERROR: Time out by %1").arg(debughere); } }
void SetStickerFuse::runTest() { QProcess avrdude; emit testMessage(testName(), infoMessage, stickerNum, QString("Setting fuse ") + fuseName + " to 0x" + QString::number(fuseValue, 16)); selectSticker(stickerNum); avrdude.start("./avrdude", QStringList() << "-C" << configFile << "-c" << "linuxgpio" << "-P" << "linuxgpio" << "-p" << partName << "-U" << (QString() + fuseName + ":w:0x" + QString::number(fuseValue, 16) + ":m") ); if (!avrdude.waitForStarted()) { testError("Unable to start avrdude"); return; } avrdude.closeWriteChannel(); if (!avrdude.waitForFinished()) { testError("avrdude never finished"); return; } if (avrdude.exitCode()) { testError(QString("avrdude returned an error: ") + avrdude.readAll()); return; } }
TTSStatus TTSFestival::voice(QString text, QString wavfile, QString* errStr) { qDebug() << "[Festival] Voicing " << text << "->" << wavfile; QString path = RbSettings::subValue("festival-client", RbSettings::TtsPath).toString(); QString cmd = QString("%1 --server localhost --otype riff --ttw --withlisp" " --output \"%2\" --prolog \"%3\" - ").arg(path).arg(wavfile).arg(prologPath); qDebug() << "[Festival] Client cmd: " << cmd; QProcess clientProcess; clientProcess.start(cmd); clientProcess.write(QString("%1.\n").arg(text).toAscii()); clientProcess.waitForBytesWritten(); clientProcess.closeWriteChannel(); clientProcess.waitForReadyRead(); QString response = clientProcess.readAll(); response = response.trimmed(); if(!response.contains("Utterance")) { qDebug() << "[Festival] Could not voice string: " << response; *errStr = tr("engine could not voice string"); return Warning; /* do not stop the voicing process because of a single string TODO: needs proper settings */ } clientProcess.closeReadChannel(QProcess::StandardError); clientProcess.closeReadChannel(QProcess::StandardOutput); clientProcess.terminate(); clientProcess.kill(); return NoError; }
int callGS( const QStringList args ) { const QString startnow = QDir::currentPath(); const QString GhostScriptPath = getGSDefaultExeName(); QDir::setCurrent(_GSCACHE_); QString cmd1 = GhostScriptPath + " "; cmd1 += args.join(" "); int fax = -1; #if defined Q_WS_MAC fax = system(cmd1.toLocal8Bit()); QDir::setCurrent(startnow); return fax; #endif QProcess *process = new QProcess(NULL); process->setReadChannelMode(QProcess::MergedChannels); process->start( GhostScriptPath , args , QIODevice::ReadOnly ); if (!process->waitForFinished()) { fax = -1; } else { QString ghostcomment = process->readAll().trimmed(); //////qDebug() << "ghostcomment-> " << ghostcomment; fax = 0; } QDir::setCurrent(startnow); return fax; }
void mainWindow::startFolding() { QProcess *proc = new QProcess(this); log->mainLogger->append("-- Starting all Folding@Home clients..."); proc->start("/etc/init.d/folding start"); proc->waitForFinished(); MSG(tr("Folding@Home / Program / Start"), tr("All clients have been successfully started!")); log->mainLogger->append("-- Showing output from : '/etc/init.d/folding start'"); QByteArray qba = proc->readAll(); QTextCodec *codec = QTextCodec::codecForLocale(); QString result = codec->toUnicode(qba); log->mainLogger->append(result); log->mainLogger->append("-- All clients have been successfully started!"); actionStart->setEnabled(false); actionStop->setEnabled(true); /* for (int l = 0; l < queue_dat->output.size(); ++l) info->mainLogger->append(queue_dat->output.at(l).toLocal8Bit().constData()); fahWuinfo *wuinfo_dat = new fahWuinfo("/home/drkameleon/foldingathome/CPU1/work/wuinfo_05.dat"); */ }
QByteArray QProcessProto::readAll() { QProcess *item = qscriptvalue_cast<QProcess*>(thisObject()); if (item) return item->readAll(); return QByteArray(); }
int Player::getTopPanel() { int topPanel = 0; #ifdef Q_WS_X11 char * pPath = getenv ("KDE_FULL_SESSION"); // KDE or Gnome if (QString(pPath) == NULL) // Gnome { QProcess gconf; gconf.start("gconftool", QStringList() << "--get" << "/schemas/apps/panel/toplevels/size"); gconf.waitForStarted(); gconf.closeWriteChannel(); gconf.waitForFinished(); QByteArray result = gconf.readAll(); QString str = QString(result); int j = 0; j = str.indexOf("Default Value:", j); int k = 0; k = str.indexOf("Owner:", k); topPanel = str.section("", j, k).trimmed().section("",-3,-1).toInt(); } #endif return topPanel; }
/* QString Process::getPippedShellCommand(QString idCommand1, QString idParam1, QString idCommand2, QString idParam2){ QString command; command = this->shsc.getPippedCommand(idCommand1, idCommand2, idParam1, idParam2); if (command.isEmpty() == false){ this->setCom(true); } else { this->setCom(false); } return command; } */ QString Process::execShellProcess(QString idCommand, QString idParam = ""){ QString result, command; QProcess *pro = NULL; //Get command command = QString(idCommand+" "+idParam); //Process command pro = new QProcess(); pro->setProcessChannelMode(QProcess::MergedChannels); pro->start(command); if (pro->waitForFinished()) { result = QString(pro->readAll()); //Trim if (result != NULL && result.isEmpty() == false){ result = result.trimmed(); } } pro->close(); //Free mem if (pro != NULL){ delete pro; } return result; }
int IDAService::DelPerson(QString username, QString db_name) { QString app_name = "IDADesktopConsole.exe"; QStringList arguments; arguments << "-m" << "DelPerson"; arguments << "-u" << username; arguments << "-w" << app_dir+"/"; arguments << "-d" << db_name; QProcess proc; proc.start(app_name,arguments); // Wait for process start if(!proc.waitForStarted()){ qDebug()<<"process start failed"; emit DelPersonFinished("NG"); return 1; } // Close write channel because we do not need it proc.closeWriteChannel(); QByteArray proc_output; while (false == proc.waitForFinished()) { qDebug()<<"Process finish failed"; emit DelPersonFinished(proc_output); return 1; } proc_output = proc.readAll(); qDebug()<<proc_output; emit DelPersonFinished(proc_output); return 0; }
/* find gpl GhostScript version */ double getGSVersion() { QProcess process; QString Stversion; bool ok; double GS_version = 0.00; QRegExp regExp1(" (\\d+)\\.(\\d+).*"); process.setReadChannelMode(QProcess::MergedChannels); process.start( getGSDefaultExeName() , QStringList() << "-v"); if (!process.waitForFinished()) { return GS_version; } else { QString pu = process.readAll(); QStringList line1 = pu.split("\n"); int pos1 = regExp1.indexIn(line1.at(0)); /* only first line */ if (pos1 > 0) { Stversion = QString("%1.%2").arg(regExp1.cap(1).toInt()).arg(regExp1.cap(2).toInt()); double GS_version = Stversion.toDouble(&ok); if (ok && GS_version > 5) { return GS_version; } } else { return GS_version; } } return GS_version; }
QStringList MasterCatalogModel::driveList() const{ QStringList drivenames; #ifdef Q_OS_WIN QFileInfoList drives = QDir::drives(); for(auto item : drives){ drivenames.append(item.filePath()); } #endif #ifdef Q_OS_LINUX QProcess process; process.start("lsblk", QStringList() << "-o" << "MOUNTPOINT"); if (process.waitForFinished()) { QByteArray result = process.readAll(); if (result.length() > 0) { QStringList mountpoints = QString(result).split('\n', QString::SplitBehavior::SkipEmptyParts); QStringList unwantedStrings("MOUNTPOINT"); unwantedStrings.append("[SWAP]"); for (QString mountp: mountpoints) { if (!unwantedStrings.contains(mountp)) drivenames.append(mountp); } } } #endif return drivenames; }
double JavaVersion() { QProcess process; QString Stversion; bool ok; double js_version = 0.00; QRegExp regExp1(" (\\d+)\\.(\\d+).*"); process.setReadChannelMode(QProcess::MergedChannels); process.start( "java" , QStringList() << "-version"); if (!process.waitForFinished()) { return js_version; } else { QString pu = process.readAll(); /////QStringList line1 = pu.split("\n"); ////////qDebug() << "### jsversion " << pu; int pos1 = regExp1.indexIn(pu); /* only first line */ if (pos1 > 0) { Stversion = QString("%1.%2").arg(regExp1.cap(1).toInt()).arg(regExp1.cap(2).toInt()); double js_version = Stversion.toDouble(&ok); if (ok && js_version > 1) { return js_version; } } else { return js_version; } } return js_version; }
QString InstallChecker::installedVersion( const QString & ) { QProcess run; run.start( "pkgutil", QStringList() << "--pkg-info-plist" << "ee.sk.idcard.estonianidcard" ); run.waitForFinished(); QXmlStreamReader xml( &run ); while( xml.readNext() != QXmlStreamReader::Invalid ) { if( !xml.isStartElement() || xml.name() != "key" || xml.readElementText() != "pkg-version" ) continue; xml.readNextStartElement(); return xml.readElementText(); } QStringList params = QStringList() << "read"; if( QFile::exists( "/var/db/receipts/ee.sk.idcard.estonianidcard.plist" ) ) params << "/var/db/receipts/ee.sk.idcard.estonianidcard" << "PackageVersion"; else params << "/Library/Receipts/estonianidcard.pkg/Contents/Info" << "CFBundleShortVersionString"; run.start( "defaults", params ); run.waitForFinished(); QByteArray result = run.readAll().trimmed(); return result.isEmpty() ? qApp->applicationVersion() : result; }
DCDCompletion QcdAssist::sendRequestToDCD(QByteArray& filedata, uint pos) { QProcess proc; proc.setProcessChannelMode(QProcess::MergedChannels); proc.start(QcdAssist::dcdClient(), QStringList() //<< QString(QLatin1String("-p%1")).arg(QcdAssist::dcdPort) << QString(QLatin1String("-c%1")).arg(pos) ); proc.write(filedata); proc.closeWriteChannel(); if(!proc.waitForFinished(QcdAssist::waitForReadyReadTimeout)) { //Core::MessageManager::write(QLatin1String("qcdassist error: unable to complete: client didn't finish in time")); proc.close(); } else if(proc.exitCode() != 0) { //Core::MessageManager::write(QString(QLatin1String("qcdassist error: unable to complete: %1")).arg(proc.exitCode())); QByteArray arr = proc.readAll(); //Core::MessageManager::write(QString::fromUtf8(arr.data(),arr.length())); } else { // everything Ok return processCompletion(proc.readAllStandardOutput()); } return DCDCompletion(); }
int main(int argc, char *argv[]) { QApplication app(argc, argv); QTextCodec::setCodecForTr( QTextCodec::codecForName("gb2312")); if (app.arguments().count() != 2) { // qFatal("Error - expected executable path as argument"); qDebug()<<QObject::tr("需要一个备份路径作为参数,如:'process /home'"); return -1; } QProcess proc; QString executable ="tar"; QStringList arguments; arguments<<"czvf"<<"backup.tar.gz"; arguments<<app.arguments().at(1); proc.start(executable, arguments); if (!proc.waitForStarted()) return false; proc.closeWriteChannel(); QByteArray procOutPut; while (!proc.waitForFinished(20)) { procOutPut = proc.readAll(); qDebug()<<procOutPut; } return EXIT_SUCCESS; }
void DlvDebugger::stepOut() { QString cmd = LiteApi::getGotools(m_liteApp); QProcess process; process.setEnvironment(LiteApi::getCurrentEnvironment(m_liteApp).toStringList()); QFileInfo info(m_lastFileName); process.setWorkingDirectory(info.path()); QStringList args; args << "finddecl" << "-file" << info.fileName() << "-line" << QString("%1").arg(m_lastFileLine+1); process.start(cmd,args); if (!process.waitForFinished(3000)) { emit debugLog(LiteApi::DebugErrorLog,"error wait find decl process"); process.kill(); return; } if (process.exitCode() != 0) { emit debugLog(LiteApi::DebugErrorLog,"error get find decl result"); return; } QByteArray data = process.readAll().trimmed(); QStringList ar = QString::fromUtf8(data).split(" "); if (ar.size() != 4 || ar[0] != "func") { emit debugLog(LiteApi::DebugErrorLog,"error find func decl in line"); return; } m_funcDecl.fileName = m_lastFileName; m_funcDecl.funcName = ar[1]; m_funcDecl.start = ar[2].toInt()-1; m_funcDecl.end = ar[3].toInt()-1; m_checkFuncDecl = true; command("next"); }
int InitDriveThread::sizeofBootFilesInKB() { QProcess proc; proc.start("du -s /mnt"); proc.waitForFinished(); return proc.readAll().split('\t').first().toInt(); }
AboutWidget::AboutWidget(QWidget *parent) : QWidget(parent) , d( new AboutWidgetPrivate ) { d->setupUi( this ); setAttribute( Qt::WA_DeleteOnClose, true ); setWindowFlags( Qt::Sheet ); QString package; #ifdef Q_OS_LINUX QProcess p; p.start( "dpkg-query", QStringList() << "-W" << "-f=${Package} ${Version}" << "estonianidcard" ); if( !p.waitForStarted() && p.error() == QProcess::FailedToStart ) { p.start( "rpm", QStringList() << "-q" << "--qf" << "%{NAME} %{VERSION}" << "estonianidcard" ); p.waitForStarted(); } p.waitForFinished(); if( !p.exitCode() ) package = "<br />" + QString::fromUtf8( p.readAll() ); p.close(); #endif d->content->setText( trUtf8( "%1 version %2, released %3%4<br /><br />" "Estonian ID-software is released by Riigi Infosüsteemide Arenduskeskus, developed by AS Sertifitseerimiskeskus<br /><br />" "Contact for assistance by email <a href=\"mailto:[email protected]\">[email protected]</a> or call 1777.") .arg( qApp->applicationName(), qApp->applicationVersion(), BUILD_DATE, package ) ); }
QString generalFunctions::getOutputFromFileMimeCmd(QString file, QString mimeArg) { try { QProcess *process = new QProcess(); QStringList *args = new QStringList(); args->append("--brief"); args->append(mimeArg); args->append(file); process->start("file", *args); if(process->waitForStarted(2000)) { process->closeWriteChannel(); process->waitForFinished(2000); QByteArray qba = process->readAll(); QTextCodec *codec = QTextCodec::codecForLocale(); QTextDecoder *decoder = codec->makeDecoder(); QString result = decoder->toUnicode(qba); delete args; delete decoder; delete process; result = result.trimmed(); return result; } else { return ""; } } catch (...) { return ""; } }