예제 #1
0
파일: util.cpp 프로젝트: hasenj/scribus
int System(const QString exename, const QStringList & args, const QString fileStdErr, const QString fileStdOut, bool* cancel)
{
    QProcess proc;
    if (!fileStdOut.isEmpty())
        proc.setStandardOutputFile(fileStdOut);
    if (!fileStdErr.isEmpty())
        proc.setStandardErrorFile(fileStdErr);
    proc.start(exename, args);
    if (proc.waitForStarted(5000))
    {
        while (!proc.waitForFinished(5000))
        {
            qApp->processEvents();
            if (cancel && (*cancel == true))
            {
                proc.kill();
                break;
            }
        }
    }
    if (cancel && (*cancel == true))
        return -1;
    int ex = proc.exitCode();
    return ex;
}
예제 #2
0
파일: AgentF.cpp 프로젝트: loh-tar/filu
void AgentF::startClone()
{
  static const int maxClones = mRcFile->getIT("MaxClones");
  static const int minJobs   = mRcFile->getIT("MinJobsPerClone");

  if(mClones.size() == maxClones or
     mClones.size() * minJobs > mCommands.size())
  {
    return;
  }

  QString logFile = mRcFile->getUrl("LogFile");

  int i = mClones.size();
  QProcess* clone = new QProcess;
  clone->setReadChannel(QProcess::StandardOutput);
  clone->setStandardErrorFile(logFile, QIODevice::Append);
  //clone->setProcessChannelMode(QProcess::MergedChannels);
  connect(clone, SIGNAL(readyRead()), this, SLOT(cloneIsReady()));
  connect(clone, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(cloneHasFinished()));
  connect(clone, SIGNAL(error(QProcess::ProcessError)), this, SLOT(cloneHasTrouble(QProcess::ProcessError)));

  mCloneNames.append(QString::number(i + 1));
  QString cmd = QString("%1 %2 %3")
                  .arg(QCoreApplication::applicationFilePath(), "do --stdin")
                  .arg(mCloneNames.at(i));

  if(mCmd->hasOpt("verbose")) cmd.append(" --verbose " + mCmd->optStr("verbose"));
  if(mConfigParms.size()) cmd.append(" --config " + mConfigParms.join(" "));

  clone->start(cmd);

  mClones.append(clone);
  verbose(FUNC, tr("Clone %1 started.").arg(mCloneNames.at(i)), eInfo);
}
예제 #3
0
파일: outputs.cpp 프로젝트: frigge/MindTree
int RSLOutputNode::compile()    const
{
    QProcess *process = new QProcess();
    QStringList arguments;
    arguments << getFileName();
    process->setStandardErrorFile("compiler.log");
    process->setWorkingDirectory(QFileInfo(getFileName()).canonicalPath());
    process->start("shaderdl", arguments);
    process->waitForFinished(10000);
    return 1;
}
예제 #4
0
QProcess* Runtime::createProcess()
{
    QProcess* process = new QProcess();

    QString logFile = this->logsDir + QString("/") + QDate::currentDate().toString() + QString("_log.txt");

    process->setStandardErrorFile(logFile, QIODevice::Append);
    process->setStandardOutputFile(logFile, QIODevice::Append);

    return process;
}
예제 #5
0
void detailwnd::enregistrer( )
{
	QString destFile = QFileDialog::getSaveFileName(this, tr("Sauver la video"),
                            "/home/dige7306/"+leAdresse->text(),
                            tr("Video (*.asf *.asx *.wsx *.wmv *.flv *.avi)"));
	if ( destFile.isEmpty() ) return;
	QStringList arg;
	/* for eurosport
	arg << "-cache";
	arg << "4096";
	arg << "-dumpstream";
	arg << "-dumpfile";
	arg << destFile;
	arg << leAdresse->text();
	QProcess::execute( "mplayer", arg );
	arg.clear();
	arg << "/usr/share/sounds/k3b_success1.wav";
	QProcess::execute( "mplayer", arg );
	*/
	/* for atdhe.net */
	arg << leAdresse->text();
	QProcess::execute( "firefox", arg );
	sleep( 5 );	/* wait for plugin to start */
	QStringList f;
	f << "Flash*";
	QStringList files = QDir::temp().entryList( f );
	qDebug() << files[0];
	arg.clear();
	arg << "-n" << "100000" << "--follow=name" << QDir::tempPath() + "/" + files[0];
	QProcess *tail = new QProcess( this );
	tail->setStandardOutputFile( destFile, QIODevice::Truncate );
	tail->setStandardErrorFile( "/tmp/tail.err", QIODevice::Truncate );
	tail->start( "tail", arg );
	if ( tail->waitForStarted() )
	{
		int msec = teDuree->time().hour() * 60 * 60 + teDuree->time().minute() * 60;
		msec *= 1000;
		if ( msec == 0 ) msec = -1;
		if ( !tail->waitForFinished(msec) )
		{
			tail->terminate();
		}
		qDebug() << " tail : " << tail->exitStatus() << " " << tail->exitCode() << endl;
	}
	else
	{
		qDebug() << " tail non demarre" << endl;
	}
}
예제 #6
0
static QString RunApp(const QString &execPath, const QString &execParam, const QString &execPipeIn="") {
    QString outPipePath = Xapi::TmpFilePath("pipeOut");

    QProcess app;
    app.setStandardInputFile(execPipeIn);
    app.setStandardOutputFile(outPipePath);
    app.setStandardErrorFile(outPipePath);
    app.start(execPath + " " + execParam);
    app.waitForFinished();

    if (QProcess::NormalExit != app.exitStatus())
        qDebug()<<app.error()<<app.errorString()<<app.state();

    QFile locale(outPipePath);
    if (!locale.open(QIODevice::ReadOnly)) {
        qDebug()<<"Open output pipe Fialed!"<<outPipePath;
        return "";
    }
    QTextStream localets(&locale);

    QString outUtf8PipePath = Xapi::TmpFilePath("utf8pipeOut");
    QFile utf8(outUtf8PipePath);
    if (!utf8.open(QIODevice::WriteOnly)) {
        qDebug()<<"Open utf8 output pipe Fialed!"<<outUtf8PipePath;
        return "";
    }
    QTextStream utf8ts(&utf8);
    utf8ts.setCodec("utf8");
    utf8ts<<localets.readAll();
    locale.close();
    utf8.close();

    utf8.open(QIODevice::ReadOnly);
    QString ret = QString(utf8.readAll());
    utf8.close();

    locale.remove();
    utf8.remove();
    return ret;
}
예제 #7
0
bool FuzzyTester::runQbs(const QString &buildDir, const QString &command, QString *errorOutput)
{
    if (errorOutput)
        errorOutput->clear();
    QProcess qbs;
    QStringList commandLine = QStringList(command) << "-d" << buildDir;
    if (m_log) {
        commandLine << "-vv";
        const size_t maxLoggedCommits = 2;
        Q_ASSERT(m_commitsWithLogFiles.size() <= maxLoggedCommits + 1);
        if (m_commitsWithLogFiles.size() == maxLoggedCommits + 1) {
            static const QStringList allActivities = QStringList() << resolveIncrementalActivity()
                    << buildIncrementalActivity() << buildFromScratchActivity();
            const QString oldCommit = m_commitsWithLogFiles.front();
            m_commitsWithLogFiles.pop();
            for (const QString &a : allActivities)
                QFile::remove(logFilePath(oldCommit, a));
        }
        qbs.setStandardErrorFile(logFilePath(m_currentCommit, m_currentActivity));
        if (m_commitsWithLogFiles.empty() || m_commitsWithLogFiles.back() != m_currentCommit)
            m_commitsWithLogFiles.push(m_currentCommit);
    } else {
        commandLine << "-qq";
    }
    if (m_jobCount != 0)
        commandLine << "--jobs" << QString::number(m_jobCount);
    commandLine << ("profile:" + m_profile);
    qbs.start("qbs", commandLine);
    if (!qbs.waitForStarted()) {
        throw TestError(QString::fromLatin1("Failed to start qbs. It is expected to be "
                "in the PATH. QProcess error string: '%1'").arg(qbs.errorString()));
    }
    if (!qbs.waitForFinished(-1) || qbs.exitCode() != 0) {
        if (errorOutput)
            *errorOutput = QString::fromLocal8Bit(qbs.readAllStandardError());
        return false;
    }
    return true;
}
예제 #8
0
QString getExecutionOutput(const QString& cmd, const QStringList& args)
{
    QProcess p;
    p.setStandardOutputFile(QDir::temp().filePath(QString().sprintf("adb-state-repair-center.%lx", long(QThread::currentThreadId()))));
    p.setStandardErrorFile(QDir::temp().filePath(QString().sprintf("adb-state-repair-center.%lx", long(QThread::currentThreadId()))));
    p.start(cmd, args);
    if (!p.waitForFinished(-1)) {
        p.kill();
        p.waitForFinished();
    } else {
        QFile result(QDir::temp().filePath(QString().sprintf("adb-state-repair-center.%lx", long(QThread::currentThreadId()))));
        result.open(QIODevice::ReadOnly);
        QString ret = result.readAll();
        ret.replace("\r", "");
        while (ret.endsWith("\n")) {
            ret.chop(1);
        }
        result.close();
        result.remove();
        return ret;
    }
    return "";

}
예제 #9
0
void QProcessProto::setStandardErrorFile(const QString &fileName, QIODevice::OpenMode mode)
{
  QProcess *item = qscriptvalue_cast<QProcess*>(thisObject());
  if (item)
    item->setStandardErrorFile(fileName, mode);
}
예제 #10
0
    ExitCodes main_(int , const char**) override
    {

      // path to the log file
      String logfile(getStringOption_("log"));
      String pepnovo_executable(getStringOption_("pepnovo_executable"));

      PeakMap exp;

      String inputfile_name = getStringOption_("in");
      writeDebug_(String("Input file: ") + inputfile_name, 1);

      String outputfile_name = getStringOption_("out");
      writeDebug_(String("Output file: ") + outputfile_name, 1);

      String model_directory = getStringOption_("model_directory");
      writeDebug_(String("model directory: ") + model_directory, 1);

      String model_name = getStringOption_("model");
      writeDebug_(String("model directory: ") + model_name, 1);

      double fragment_tolerance = getDoubleOption_("fragment_tolerance");
      if (fragment_tolerance!=-1.0 && (fragment_tolerance<0 || fragment_tolerance>0.75))
      {
        writeLog_("Invalid fragment tolerance");
        printUsage_();
        return ILLEGAL_PARAMETERS;
      }

      double pm_tolerance = getDoubleOption_("pm_tolerance");
      if (pm_tolerance!=-1.0 && (pm_tolerance<0.0 || pm_tolerance>5.0))
      {
        writeLog_("Invalid fragment tolerance");
        printUsage_();
        return ILLEGAL_PARAMETERS;
      }

      Int tag_length = getIntOption_("tag_length");
      if ( tag_length!=-1 && (tag_length<3 || tag_length>6))
      {
        writeLog_("Invalid fragment tolerance");
        printUsage_();
        return ILLEGAL_PARAMETERS;
      }
      String digest = getStringOption_("digest");
      Size num_solutions=getIntOption_("num_solutions");

      //-------------------------------------------------------------
      // reading input
      //-------------------------------------------------------------

      // only load msLevel 2
      MzMLFile mzml_infile;
      mzml_infile.getOptions().addMSLevel(2);
      mzml_infile.setLogType(log_type_);
      mzml_infile.load(inputfile_name, exp);

      // we map the native id to the MZ and RT to be able to
      // map the IDs back to the spectra (RT, and MZ Meta Information)
      PepNovoOutfile::IndexPosMappingType index_to_precursor;
      for (Size i = 0; i < exp.size(); ++i)
      {
        index_to_precursor[i]= make_pair(exp[i].getRT(), exp[i].getPrecursors()[0].getPosition()[0]); //set entry <RT, MZ>
      }

      logfile = getStringOption_("log");
      
      QDir qdir_models_source(model_directory.c_str());
      if (!qdir_models_source.exists())
      {
        writeLog_("The model directory does not exist");
        return INPUT_FILE_NOT_FOUND;
      }
      
      // create temp directory
      QDir qdir_temp(File::getTempDirectory().toQString());
      String temp_data_directory = File::getUniqueName();
      qdir_temp.mkdir(temp_data_directory.toQString());
      qdir_temp.cd(temp_data_directory.toQString());
      temp_data_directory  = File::getTempDirectory() + "/" + temp_data_directory; // delete later

      String mgf_file = temp_data_directory + "/" + File::getUniqueName() + ".mgf"; // the mzXML parser of PepNovo is somewhat broken.. don't use mzXML
      MascotGenericFile().store(mgf_file, exp);

      bool error(false);

      try
      {
        //temporary File to store PepNovo output
        String temp_pepnovo_outfile = qdir_temp.absoluteFilePath("tmp_pepnovo_out.txt");
        String tmp_models_dir = qdir_temp.absoluteFilePath("Models");

        std::map<String, String>mods_and_keys; //, key_to_id;

        if (qdir_temp.cd("Models"))
        {
          writeLog_("The temporary directory already contains \"Model\" Folder. Please delete it and re-run. Aborting!");
          return CANNOT_WRITE_OUTPUT_FILE;
        }
        else
        {
          qdir_temp.mkdir("Models");
          qdir_temp.cd("Models");
        }

        //copy the Models folder of OpenMS into the temp_data_directory
        QStringList pepnovo_files = qdir_models_source.entryList(QDir::Dirs | QDir::Files|QDir::NoDotAndDotDot);
        if (pepnovo_files.empty())
        {
          writeLog_("The \"Model\" directory does not contain model files. Aborting!");
          return INPUT_FILE_NOT_FOUND;
        }

        for (QStringList::ConstIterator file_it=pepnovo_files.begin(); file_it!=pepnovo_files.end(); ++file_it)
        {
          if (qdir_models_source.cd(*file_it))
          {
            qdir_temp.mkdir(*file_it);
            qdir_temp.cd(*file_it);
            QStringList subdir_files = qdir_models_source.entryList(QDir::Dirs | QDir::Files|QDir::NoDotAndDotDot);
            for (QStringList::ConstIterator subdir_file_it=subdir_files.begin(); subdir_file_it!=subdir_files.end(); ++subdir_file_it)
            {
              QFile::copy(qdir_models_source.filePath(*subdir_file_it), qdir_temp.filePath(*subdir_file_it));
            }
            qdir_temp.cdUp();
            qdir_models_source.cdUp();
          }
          else
          {
            QFile::copy(qdir_models_source.filePath(*file_it), qdir_temp.filePath(*file_it));
          }
        }

        //generate PTM File and store in temp directory
        PepNovoInfile p_novo_infile;
        String ptm_command;
        if (!getStringList_("fixed_modifications").empty() || !getStringList_("variable_modifications").empty())
        {
          p_novo_infile.setModifications(getStringList_("fixed_modifications"), getStringList_("variable_modifications"));
          p_novo_infile.store(qdir_temp.filePath("PepNovo_PTMs.txt"));
          pepnovo_files.append("PepNovo_PTMs.txt");
          p_novo_infile.getModifications(mods_and_keys);

          for (std::map<String, String>::const_iterator key_it=mods_and_keys.begin(); key_it!=mods_and_keys.end();++key_it)
          {
            if (ptm_command!="")
            {
              ptm_command+=":";
            }
            ptm_command+= key_it->first;
            //key_to_id[key_it->second]=key_it->first;
          }
        }

        //-------------------------------------------------------------
        // (3) running program according to parameters
        //-------------------------------------------------------------
        QStringList arguments;

        arguments << "-file" << mgf_file.toQString();
        arguments << "-model" << model_name.toQString();
        if (pm_tolerance != -1 ) arguments << "-pm_tolerance"<<String(pm_tolerance).toQString();
        if (fragment_tolerance != -1 ) arguments << "-fragment_tolerance" <<String(fragment_tolerance).toQString();
        if (!ptm_command.empty()) arguments <<"-PTMs" <<ptm_command.toQString();
        if (getFlag_("correct_pm")) arguments << "-correct_pm";
        if (getFlag_("use_spectrum_charge")) arguments << "-use_spectrum_charge";
        if (getFlag_("use_spectrum_mz")) arguments << "-use_spectrum_mz";
        if (getFlag_("no_quality_filter")) arguments << "-no_quality_filter";
        arguments << "-digest" << digest.toQString();
        arguments << "-num_solutions" << String(num_solutions).toQString();
        if (tag_length!=-1) arguments<<"-tag_length" << String(tag_length).toQString();
        arguments<<"-model_dir" << tmp_models_dir.toQString();
        //arguments<<">" << temp_pepnovo_outfile.toQString();

        writeDebug_("Use this line to call PepNovo: ", 1);
        writeDebug_(pepnovo_executable + " " + String(arguments.join(" ")), 1);
        QProcess process;
        process.setStandardOutputFile(temp_pepnovo_outfile.toQString());
        process.setStandardErrorFile(temp_pepnovo_outfile.toQString());
        process.start(pepnovo_executable.toQString(), arguments); // does automatic escaping etc...
        if (process.waitForFinished(-1))
        {
          //if PepNovo finished successfully use PepNovoOutfile to parse the results and generate idXML
          std::vector< PeptideIdentification > peptide_identifications;
          ProteinIdentification protein_identification;
          StringList ms_runs;
          exp.getPrimaryMSRunPath(ms_runs);
          protein_identification.setPrimaryMSRunPath(ms_runs);

          PepNovoOutfile p_novo_outfile;

          //resolve PTMs (match them back to the OpenMs Identifier String)
          std::vector<ProteinIdentification>prot_ids;
          p_novo_outfile.load(temp_pepnovo_outfile, peptide_identifications, protein_identification, -1e5, index_to_precursor, mods_and_keys);
          prot_ids.push_back(protein_identification);
          IdXMLFile().store(outputfile_name, prot_ids, peptide_identifications);
        }

        if (process.exitStatus() != 0)  error = true;
       
      }
      catch(Exception::BaseException &exc)
      {
        writeLog_(exc.what());
        LOG_ERROR << "Error occurred: " << exc.what() << std::endl;
        error = true;
      }
      
      if (!error)
      {
        File::removeDirRecursively(temp_data_directory);
        return EXECUTION_OK;
      }
      else
      {
        writeLog_("PepNovo problem. Aborting! (Details can be seen in outfiles: '" + temp_data_directory + "')");
        return EXTERNAL_PROGRAM_ERROR;
      }

    }
예제 #11
0
void AssignmentClientMonitor::spawnChildClient() {
    QProcess* assignmentClient = new QProcess(this);

    // unparse the parts of the command-line that the child cares about
    QStringList _childArguments;
    if (_assignmentPool != "") {
        _childArguments.append("--" + ASSIGNMENT_POOL_OPTION);
        _childArguments.append(_assignmentPool);
    }
    if (!_walletUUID.isNull()) {
        _childArguments.append("--" + ASSIGNMENT_WALLET_DESTINATION_ID_OPTION);
        _childArguments.append(_walletUUID.toString());
    }
    if (_assignmentServerHostname != "") {
        _childArguments.append("--" + CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION);
        _childArguments.append(_assignmentServerHostname);
    }
    if (_assignmentServerPort != DEFAULT_DOMAIN_SERVER_PORT) {
        _childArguments.append("--" + CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION);
        _childArguments.append(QString::number(_assignmentServerPort));
    }
    if (_requestAssignmentType != Assignment::AllTypes) {
        _childArguments.append("--" + ASSIGNMENT_TYPE_OVERRIDE_OPTION);
        _childArguments.append(QString::number(_requestAssignmentType));
    }

    // tell children which assignment monitor port to use
    // for now they simply talk to us on localhost
    _childArguments.append("--" + ASSIGNMENT_CLIENT_MONITOR_PORT_OPTION);
    _childArguments.append(QString::number(DependencyManager::get<NodeList>()->getLocalSockAddr().getPort()));

    _childArguments.append("--" + PARENT_PID_OPTION);
    _childArguments.append(QString::number(QCoreApplication::applicationPid()));

    QString nowString, stdoutFilenameTemp, stderrFilenameTemp, stdoutPathTemp, stderrPathTemp;


    if (_wantsChildFileLogging) {
        // Setup log files
        const QString DATETIME_FORMAT = "yyyyMMdd.hh.mm.ss.zzz";

        if (!_logDirectory.exists()) {
            qDebug() << "Log directory (" << _logDirectory.absolutePath() << ") does not exist, creating.";
            _logDirectory.mkpath(_logDirectory.absolutePath());
        }

        nowString = QDateTime::currentDateTime().toString(DATETIME_FORMAT);
        stdoutFilenameTemp = QString("ac-%1-stdout.txt").arg(nowString);
        stderrFilenameTemp = QString("ac-%1-stderr.txt").arg(nowString);
        stdoutPathTemp = _logDirectory.absoluteFilePath(stdoutFilenameTemp);
        stderrPathTemp = _logDirectory.absoluteFilePath(stderrFilenameTemp);

        // reset our output and error files
        assignmentClient->setStandardOutputFile(stdoutPathTemp);
        assignmentClient->setStandardErrorFile(stderrPathTemp);
    }

    // make sure that the output from the child process appears in our output
    assignmentClient->setProcessChannelMode(QProcess::ForwardedChannels);
    assignmentClient->start(QCoreApplication::applicationFilePath(), _childArguments);

#ifdef Q_OS_WIN
    addProcessToGroup(PROCESS_GROUP, assignmentClient->processId());
#endif

    QString stdoutPath, stderrPath;

    if (_wantsChildFileLogging) {

        // Update log path to use PID in filename
        auto stdoutFilename = QString("ac-%1_%2-stdout.txt").arg(nowString).arg(assignmentClient->processId());
        auto stderrFilename = QString("ac-%1_%2-stderr.txt").arg(nowString).arg(assignmentClient->processId());
        stdoutPath = _logDirectory.absoluteFilePath(stdoutFilename);
        stderrPath = _logDirectory.absoluteFilePath(stderrFilename);

        qDebug() << "Renaming " << stdoutPathTemp << " to " << stdoutPath;
        if (!_logDirectory.rename(stdoutFilenameTemp, stdoutFilename)) {
            qDebug() << "Failed to rename " << stdoutFilenameTemp;
            stdoutPath = stdoutPathTemp;
            stdoutFilename = stdoutFilenameTemp;
        }

        qDebug() << "Renaming " << stderrPathTemp << " to " << stderrPath;
        if (!QFile::rename(stderrPathTemp, stderrPath)) {
            qDebug() << "Failed to rename " << stderrFilenameTemp;
            stderrPath = stderrPathTemp;
            stderrFilename = stderrFilenameTemp;
        }
        
        qDebug() << "Child stdout being written to: " << stdoutFilename;
        qDebug() << "Child stderr being written to: " << stderrFilename;
    }

    if (assignmentClient->processId() > 0) {
        auto pid = assignmentClient->processId();
        // make sure we hear that this process has finished when it does
        connect(assignmentClient, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
                this, [this, pid](int exitCode, QProcess::ExitStatus exitStatus) {
                    childProcessFinished(pid, exitCode, exitStatus);
            });

        qDebug() << "Spawned a child client with PID" << assignmentClient->processId();

        _childProcesses.insert(assignmentClient->processId(), { assignmentClient, stdoutPath, stderrPath });
    }
}