本文整理汇总了C++中QProcess::error方法的典型用法代码示例。如果您正苦于以下问题:C++ QProcess::error方法的具体用法?C++ QProcess::error怎么用?C++ QProcess::error使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QProcess
的用法示例。
在下文中一共展示了QProcess::error方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: createDocumentationFile
void UncrustifySettings::createDocumentationFile() const
{
QProcess process;
process.start(command(), QStringList() << QLatin1String("--show-config"));
process.waitForFinished(2000); // show config should be really fast.
if (process.error() != QProcess::UnknownError)
return;
QFile file(documentationFilePath());
const QFileInfo fi(file);
if (!fi.exists())
fi.dir().mkpath(fi.absolutePath());
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
return;
bool contextWritten = false;
QXmlStreamWriter stream(&file);
stream.setAutoFormatting(true);
stream.writeStartDocument(QLatin1String("1.0"), true);
stream.writeComment(QLatin1String("Created ")
+ QDateTime::currentDateTime().toString(Qt::ISODate));
stream.writeStartElement(QLatin1String(Constants::DOCUMENTATION_XMLROOT));
const QStringList lines = QString::fromUtf8(process.readAll()).split(QLatin1Char('\n'));
const int totalLines = lines.count();
for (int i = 0; i < totalLines; ++i) {
const QString &line = lines.at(i);
if (line.startsWith(QLatin1Char('#')) || line.trimmed().isEmpty())
continue;
const int firstSpace = line.indexOf(QLatin1Char(' '));
const QString keyword = line.left(firstSpace);
const QString options = line.right(line.size() - firstSpace).trimmed();
QStringList docu;
while (++i < totalLines) {
const QString &subline = lines.at(i);
if (line.startsWith(QLatin1Char('#')) || subline.trimmed().isEmpty()) {
const QString text = QLatin1String("<p><span class=\"option\">") + keyword
+ QLatin1String("</span> <span class=\"param\">") + options
+ QLatin1String("</span></p><p>")
+ (docu.join(QLatin1Char(' ')).toHtmlEscaped())
+ QLatin1String("</p>");
stream.writeStartElement(QLatin1String(Constants::DOCUMENTATION_XMLENTRY));
stream.writeTextElement(QLatin1String(Constants::DOCUMENTATION_XMLKEY), keyword);
stream.writeTextElement(QLatin1String(Constants::DOCUMENTATION_XMLDOC), text);
stream.writeEndElement();
contextWritten = true;
break;
} else {
docu << subline;
}
}
}
stream.writeEndElement();
stream.writeEndDocument();
// An empty file causes error messages and a contextless file preventing this function to run
// again in order to generate the documentation successfully. Thus delete the file.
if (!contextWritten) {
file.close();
file.remove();
}
}
示例2: processDownload
void KbFirmware::processDownload(QNetworkReply* reply){
if(reply->error() != QNetworkReply::NoError)
return;
// Update last check
lastCheck = lastFinished = QDateTime::currentMSecsSinceEpoch();
QByteArray data = reply->readAll();
// Don't do anything if this is the same as the last version downloaded
QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Sha256);
if(hash == fwTableHash)
return;
fwTableHash = hash;
if(hasGPG == UNKNOWN){
// Check for a GPG installation
QProcess gpg;
gpg.start("gpg", QStringList("--version"));
gpg.waitForFinished();
if(gpg.error() == QProcess::FailedToStart)
// No GPG install
hasGPG = NO;
else {
QString output = QString::fromUtf8(gpg.readAll());
// Must support RSA keys and SHA256
if(output.contains("RSA", Qt::CaseInsensitive) && output.contains("SHA256", Qt::CaseInsensitive))
hasGPG = YES;
else
hasGPG = NO;
}
if(!hasGPG)
qDebug() << "No GPG detected, signature verification disabled";
}
if(hasGPG){
// If GPG is available, check the signature on the file before proceeding.
QDir tmp = QDir::temp();
// Save file to a temporary path. Include PID to avoid conflicts
qint64 pid = QCoreApplication::applicationPid();
QString fwPath = tmp.absoluteFilePath(QString("ckb-%1-firmware").arg(pid));
QFile firmware(fwPath);
if(!firmware.open(QIODevice::WriteOnly)
|| firmware.write(data) != data.length()){
qDebug() << "Failed to write firmware file to temporary location, aborting firmware check";
return;
}
firmware.close();
// Write GPG key
QString keyPath = tmp.absoluteFilePath(QString("ckb-%1-key.gpg").arg(pid));
if(!QFile::copy(":/bin/msckey.gpg", keyPath)){
firmware.remove();
qDebug() << "Failed to write GPG key to temporary location, aborting firmware check";
return;
}
// Check signature
QProcess gpg;
gpg.start("gpg", QStringList("--no-default-keyring") << "--keyring" << keyPath << "--verify" << fwPath);
gpg.waitForFinished();
// Clean up temp files
tmp.remove(fwPath);
tmp.remove(keyPath);
if(gpg.error() != QProcess::UnknownError || gpg.exitCode() != 0){
qDebug() << "GPG couldn't verify firmware signature:";
qDebug() << gpg.readAllStandardOutput();
qDebug() << gpg.readAllStandardError();
return;
}
// Signature good, proceed to update database
}
fwTable.clear();
QStringList lines = QString::fromUtf8(data).split("\n");
bool scan = false;
foreach(QString line, lines){
// Collapse whitespace
line.replace(QRegExp("\\s+"), " ").remove(QRegExp("^\\s")).remove(QRegExp("\\s$"));
// Skip empty or commented-out lines
if(line.length() == 0 || line.at(0) == '#')
continue;
// Don't read anything until the entries begin and don't read anything after they end
if(!scan){
if(line == "!BEGIN FW ENTRIES")
scan = true;
else
continue;
}
if(line == "!END FW ENTRIES")
break;
QStringList components = line.split(" ");
if(components.length() != 7)
continue;
// "VENDOR-PRODUCT"
QString device = components[0].toUpper() + "-" + components[1].toUpper();
FW fw;
fw.fwVersion = components[2].toFloat(); // Firmware blob version
fw.url = QUrl::fromPercentEncoding(components[3].toLatin1()); // URL to zip file
fw.ckbVersion = PARSE_CKB_VERSION(components[4]); // Minimum ckb version
fw.fileName = QUrl::fromPercentEncoding(components[5].toLatin1()); // Name of file inside zip
fw.hash = QByteArray::fromHex(components[6].toLatin1()); // SHA256 of file inside zip
// Update entry
fwTable[device] = fw;
}
示例3: main
int main(int argc, char** argv)
{
QApplication myApp(argc, argv);
myApp.setOrganizationName("CommonTK");
myApp.setApplicationName("CommandLineModuleExplorer");
ctkCommandLineParser cmdLineParser;
cmdLineParser.setArgumentPrefix("--", "-");
cmdLineParser.setStrictModeEnabled(true);
cmdLineParser.addArgument("module", "", QVariant::String, "Path to a CLI module (executable)");
//cmdLineParser.addArgument("module-xml", "", QVariant::String, "Path to a CLI XML description.");
cmdLineParser.addArgument("validate-module", "", QVariant::String, "Path to a CLI module");
cmdLineParser.addArgument("validate-xml", "", QVariant::String, "Path to a CLI XML description.");
cmdLineParser.addArgument("verbose", "v", QVariant::Bool, "Be verbose.");
cmdLineParser.addArgument("help", "h", QVariant::Bool, "Print this help text.");
bool parseOkay = false;
QHash<QString, QVariant> args = cmdLineParser.parseArguments(argc, argv, &parseOkay);
QTextStream out(stdout, QIODevice::WriteOnly);
if(!parseOkay)
{
out << "Error parsing command line arguments: " << cmdLineParser.errorString() << '\n';
return EXIT_FAILURE;
}
if (args.contains("help"))
{
out << "Usage:\n" << cmdLineParser.helpText();
out.flush();
return EXIT_SUCCESS;
}
if (args.contains("validate-module"))
{
if (args.contains("validate-xml"))
{
out << "Ignoring \"validate-xml\" option.\n\n";
}
QString input = args["validate-module"].toString();
if (!QFile::exists(input))
{
qCritical() << "Module does not exist:" << input;
return EXIT_FAILURE;
}
QProcess process;
process.setReadChannel(QProcess::StandardOutput);
process.start(input, QStringList("--xml"));
if (!process.waitForFinished() || process.exitStatus() == QProcess::CrashExit ||
process.error() != QProcess::UnknownError)
{
qWarning() << "The executable at" << input << "could not be started:" << process.errorString();
return EXIT_FAILURE;
}
process.waitForReadyRead();
QByteArray xml = process.readAllStandardOutput();
if (args.contains("verbose"))
{
qDebug() << xml;
}
// validate the outputted xml description
QBuffer xmlInput(&xml);
xmlInput.open(QIODevice::ReadOnly);
ctkCmdLineModuleXmlValidator validator(&xmlInput);
if (!validator.validateInput())
{
qCritical() << validator.errorString();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
else if (args.contains("validate-xml"))
{
QFile input(args["validate-xml"].toString());
if (!input.exists())
{
qCritical() << "XML description does not exist:" << input.fileName();
return EXIT_FAILURE;
}
input.open(QIODevice::ReadOnly);
ctkCmdLineModuleXmlValidator validator(&input);
if (!validator.validateInput())
{
qCritical() << validator.errorString();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
//.........这里部分代码省略.........
示例4: DirectoryMangaVolume
CompressedFileMangaVolume::CompressedFileMangaVolume(const QString & filepath, QObject *parent, bool do_cleanup)
: DirectoryMangaVolume(parent), m_do_cleanup(do_cleanup) {
QStringList path_split = filepath.split("/");
QString filename = path_split.last();
QStringList filename_split = filename.split(".");
if (filename_split.length() > 1) {
filename_split.pop_back();
}
QDir dir;
do {
// keep trying hashes until dir exists.
// no one could have taken all hashes
QTime time = QTime::currentTime();
QString toHash = filepath+time.toString();
qWarning() << toHash;
QString hash = QString(QCryptographicHash::hash(
toHash.toAscii(),
QCryptographicHash::Sha1).toHex());
m_file_dir = tr("/tmp/") + filename_split.join(tr("."))
+ tr("-") + hash;
qWarning() << "Making directory: " << m_file_dir;
dir = QDir(m_file_dir);
} while (dir.exists());
dir.mkpath(".");
QString program = "";
QStringList arguments;
if (filename.endsWith(tr(".zip"))) {
program = tr("unzip");
arguments << tr("-d") << m_file_dir;
arguments << filepath;
} else if (filename.endsWith(tr(".rar"))) {
program = tr("unrar");
arguments << tr("x");
arguments << filepath;
arguments << m_file_dir;
} else {
qWarning() << "Unknown filetype for file " << filename;
return;
}
qWarning() << "Open file?: " << filename;
QProcess * myProcess = new QProcess(this);
// Start the extraction program
myProcess->start(program, arguments);
// Check to make sure it started correctly
if (!myProcess->waitForStarted()) {
switch (myProcess->error()) {
case QProcess::FailedToStart:
qWarning() << "Failed to start program" << program << ". Is it installed correctly?";
break;
case QProcess::Crashed:
qWarning() << "Program" << program << "crashed.";
break;
default:
qWarning() << "QProcess::ProcessError code " << myProcess->error();
}
return;
}
// Check to make sure it finished correctly
if (!myProcess->waitForFinished()) {
qWarning() << program << "was unable to extract file " << filepath;
// TODO(umbrant): capture stdout/stderr to show the user
return;
}
// Successful extraction
qWarning() << "Extracted successfully";
m_do_cleanup = true;
readImages(m_file_dir);
for (const MangaPage& page: m_pages) {
page.getFilename().size();
// TODO(mtao): processing?
}
}
示例5: import
//.........这里部分代码省略.........
noDataValue = std::numeric_limits<double>::max() * -1.0;
break;
default: // should not happen
noDataValue = std::numeric_limits<double>::max() * -1.0;
}
for ( qgssize i = 0; i < ( qgssize )block->width()*block->height(); i++ )
{
if ( block->isNoData( i ) )
{
block->setValue( i, noDataValue );
}
}
}
char * data = block->bits( row, 0 );
int size = iterCols * block->dataTypeSize();
QByteArray byteArray = QByteArray::fromRawData( data, size ); // does not copy data and does not take ownership
if ( isCanceled() )
{
outStream << true; // cancel module
break;
}
outStream << false; // not canceled
outStream << noDataValue;
outStream << byteArray;
// Without waitForBytesWritten() it does not finish ok on Windows (process timeout)
process->waitForBytesWritten( -1 );
#ifndef Q_OS_WIN
// wait until the row is written to allow quick cancel (don't send data to buffer)
process->waitForReadyRead();
bool result;
outStream >> result;
#endif
}
delete block;
if ( isCanceled() )
{
outStream << true; // cancel module
break;
}
}
// TODO: send something back from module and read it here to close map correctly in module
process->closeWriteChannel();
// TODO: best timeout?
process->waitForFinished( 30000 );
QString stdoutString = process->readAllStandardOutput().data();
QString stderrString = process->readAllStandardError().data();
QString processResult = QString( "exitStatus=%1, exitCode=%2, error=%3, errorString=%4 stdout=%5, stderr=%6" )
.arg( process->exitStatus() ).arg( process->exitCode() )
.arg( process->error() ).arg( process->errorString() )
.arg( stdoutString.replace( "\n", ", " ) ).arg( stderrString.replace( "\n", ", " ) );
QgsDebugMsg( "processResult: " + processResult );
if ( process->exitStatus() != QProcess::NormalExit )
{
setError( process->errorString() );
delete process;
return false;
}
if ( process->exitCode() != 0 )
{
setError( stderrString );
delete process;
return false;
}
delete process;
}
QgsDebugMsg( QString( "redBand = %1 greenBand = %2 blueBand = %3" ).arg( redBand ).arg( greenBand ).arg( blueBand ) );
if ( redBand > 0 && greenBand > 0 && blueBand > 0 )
{
// TODO: check if the group exists
// I_find_group()
QString name = mGrassObject.name();
G_TRY
{
QgsGrass::setMapset( mGrassObject.gisdbase(), mGrassObject.location(), mGrassObject.mapset() );
struct Ref ref;
I_get_group_ref( name.toUtf8().data(), &ref );
QString redName = name + QString( ".%1" ).arg( redBand );
QString greenName = name + QString( ".%1" ).arg( greenBand );
QString blueName = name + QString( ".%1" ).arg( blueBand );
I_add_file_to_group_ref( redName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref );
I_add_file_to_group_ref( greenName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref );
I_add_file_to_group_ref( blueName.toUtf8().data(), mGrassObject.mapset().toUtf8().data(), &ref );
I_put_group_ref( name.toUtf8().data(), &ref );
}
G_CATCH( QgsGrass::Exception &e )
{
QgsDebugMsg( QString( "Cannot create group: %1" ).arg( e.what() ) );
}
示例6: generate
bool generate(const ToolListType & tools, const String & prefix, const String & binary_directory)
{
bool errors_occured = false;
for (ToolListType::const_iterator it = tools.begin(); it != tools.end(); ++it)
{
//start process
QProcess process;
process.setProcessChannelMode(QProcess::MergedChannels);
QStringList env = QProcess::systemEnvironment();
env << String("COLUMNS=110").toQString(); // Add an environment variable (used by each TOPP tool to determine width of help text (see TOPPBase))
process.setEnvironment(env);
String command = binary_directory + it->first;
#if defined(__APPLE__)
if (it->first == "TOPPView" || it->first == "TOPPAS")
{
command = binary_directory + it->first + ".app/Contents/MacOS/" + it->first;
}
#endif
#ifdef OPENMS_WINDOWSPLATFORM
command += ".exe"; // otherwise File::exists() will fail
#endif
ofstream f((String("output/") + prefix + it->first + ".cli").c_str());
if (!File::exists(command))
{
stringstream ss;
ss << "Errors occurred while generating the command line documentation for " << it->first << "!" << endl;
ss << "Tool could not be found at '" << command << "'\n " << command << endl;
f << ss.str();
cerr << ss.str();
errors_occured = true;
f.close();
continue;
}
else
{
process.start(String(command + " --help").toQString());
process.waitForFinished();
std::string lines = QString(process.readAll()).toStdString();
if (process.error() != QProcess::UnknownError)
{
// error while generation cli docu
stringstream ss;
f << "Errors occurred while generating the command line documentation for " << it->first << "!" << endl;
f << "Output was: \n" << lines << endl;
f << "Command line was: \n " << command << endl;
f << ss.str();
cerr << ss.str();
errors_occured = true;
f.close();
continue;
}
else
{
// write output
f << lines;
}
}
f.close();
//////
// get the INI file and convert it into HTML
//////
if (it->first == "GenericWrapper")
continue; // does not support -write_ini without a type
if (it->first == "TOPPView")
continue; // does not support -write_ini
if (it->first == "TOPPAS")
continue; // does not support -write_ini
String tmp_file = File::getTempDirectory() + "/" + File::getUniqueName() + "_" + it->first + ".ini";
process.start((command + " -write_ini " + tmp_file).toQString());
process.waitForFinished();
Param p;
ParamXMLFile pf;
pf.load(tmp_file, p);
File::remove(tmp_file);
ofstream f_html((String("output/") + prefix + it->first + ".html").c_str());
convertINI2HTML(p, f_html);
f_html.close();
}
return errors_occured;
}
示例7: executeScript
// actually execute the command here
int AdminThread::executeScript(const QString &command)
{
// Qt standard stream output
QTextStream out(stdout);
//out << tr("Qt signing out from thread!!") << endl;
int i;
int &ref = i;
QString str;
emit signalOutput(command);
emit signalOutput("\n");
// debugging output in threads works
//qDebug("Hello world from thread!");
// C++ standard stream output
//cout << "Goodbye World from thread!!" << endl;
//str = tr("Goodbye World 2!");
//cout << str.toStdString() << endl;
//fflush(stdout);
out << tr("about to start: %1").arg(command) << endl;
QProcess process;
//process.start("/home/oliver/projects/vm/test");
process.start(command);
// now read the output line by line
// and send to calling thread
//char buf[1024];
//qint64 lineLength;
QString stdout;
if (!process.waitForStarted())
return false;
// signal process is now running
running = true;
emit signalRunning(running);
out << tr("started: %1").arg(command) << endl;
while (!stop && !abort) {
// wait for output on timeout or process finished for some reason
if (!process.waitForReadyRead()) {
// process finished for some reason so exit from output loop
out << tr("nothing left to read") << endl;
break;
}
stdout = process.readAllStandardOutput();
//lineLength = process.readLine(buf, sizeof(buf));
//if (lineLength == -1) {
// end of stream
// break;
//}
emit signalOutput(stdout);
out << tr("line...") << endl;
//emit signalOutput("zzz\n");
}
int ec = process.exitCode();
int es = process.exitStatus();
int er = process.error();
int st = process.state();
out << "Exit code: " + QString::number(ec) << endl;
out << "Exit status: " + QString::number(es) << endl;
out << "Error: " + QString::number(er) << endl;
out << "State: " + QString::number(st) << endl;
// wait for process to terminate, if it hasn't stopped already
process.close();
out << tr("finished: %1").arg(command) << endl;
ec = process.exitCode(); // exit code from process run eg
// 0 - exit OK
// 1 - exit with some error
es = process.exitStatus(); // 0 - OK
// 1 - crash/kill
er = process.error(); // 0 - failed to start
// 1 - crashed
// 2 - timedout - can recall waitFor
// 3 - write error
// 4 - read error
// 5 - unknown (default)
st = process.state(); // 0 - not running
// 1 - starting
// 2 - running
out << "Exit code: " + QString::number(ec) << endl;
out << "Exit status: " + QString::number(es) << endl;
out << "Error: " + QString::number(er) << endl;
out << "State: " + QString::number(st) << endl;
//if (!process.waitForFinished())
// return false;
//process.waitForFinished(-1); // will wait forever until finished
//.........这里部分代码省略.........
示例8: main
int main(int argc, char *argv[])
{
try {
QApplication app(argc, argv);
QString commands;
//Mac specific Terminal command
commands = "system_profiler SPHardwareDataType";
//commands = "cat abc"; /* Wrong cat file -- testing */
//commands = " abc"; /* Wrong Terminal command -- testing */
/* For Linux and Ubuntu we use -- cat /proc/cpuinfo*/
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QProcess *process = new QProcess(0);
process->setProcessChannelMode(QProcess::MergedChannels);
//process->start("system_profiler SPHardwareDataType");
process->start(commands);
QByteArray arrSysInfo;
process->write(arrSysInfo);
process->closeWriteChannel();
if(!process->waitForStarted()){
qDebug() << "Could not wait to start..."
<< process->error()
<< process->errorString();
}
if(!process->waitForFinished()) {
qDebug() << "Could not wait to finish..."
<< process->error()
<< process->errorString();
}
else{
mySysInfo output; /* interface */
output.setData( process->readAll());
QObject *rootObject = engine.rootObjects().first();
QObject* lstview = rootObject->findChild<QObject*>("lstview");
if (lstview)
lstview->setProperty("placeholderText", output.getData());//quick fix
}
return app.exec();
} catch(std::exception e) {\
qDebug() << "Exception caught in main()"
<< e.what();
}
}
示例9: _run_stuff
void TestBinRunner::_run_stuff()
{
///
/// initialization
// get arguments
// avoid first argument (i.e., parent binary)
QStringList args;
for (int i = 1; i < _argc; i++)
args << _argv[i];
// declare process and output binder
QProcess* pro;
QtOutputBinder* qob;
///
/// execute tests binaries
for (std::list<TestSuiteDescriptor>::const_iterator ci = _testbins.begin();
ci != _testbins.end();
++ci){
// get path and name
QString binid((*ci).id.c_str());
QString binpath((*ci).path.c_str());
QString bindesc((*ci).description.c_str());
_running_instance = (*ci);
std::cout << "+---------------------------------------------------------" << std::endl
<< " Executing: " << binpath.toStdString() << std::endl;
// execute test bin
// create process and connect output
pro = new QProcess();
qob = new QtOutputBinder(pro);
qob->set_enabled(true);// enable for debugging
// connect signal handlers
pro->connect(pro,SIGNAL(error(QProcess::ProcessError)),this, SLOT(_qprocess_error_handler(QProcess::ProcessError)));
//pro->connect(pro,SIGNAL(finished(int,QProcess::ExitStatus)),this, SLOT(_qprocess_finished_handler(int,QProcess::ExitStatus)));
// execute binary and wait for it
pro->start(binpath,args,QIODevice::ReadWrite | QIODevice::Text);
if(!pro->waitForFinished()) // beware the timeout default parameter
{
std::cerr << "Error: Executing program failed with exit code " << pro->exitCode() << std::endl;
_qprocess_error_handler(pro->error());
}
// do output stuff
std::cout << " Collecting output" << std::endl;
_do_output_options();
// clean
pro->close();
delete pro; delete qob;
std::cout << " Finished" << std::endl;
// sleep if set
_check_pause_between();
}
}