问题
I use system() command in Qt. and I want to get output and show it to users. my command is:
system("echo '" + rootPass.toAscii() + "' | su - root -c 'yum -y install " + packageName.toAscii() + "'");
this command can't run when I use it in QProcess (start or execute function)
but if i can run this command in QProcess i can get output with QProcess::readAllStandardOutput()
function.
also when i used ">" in system command to save output in a file, I receive output when the package completely installed. like bellow:
system("echo '" + rootPass.toAscii() + "' | su - root -c 'yum -y install " + packageName.toAscii() + "' > result.out");
is there any idea about running this command with QProcess, or get output from system() command as soon as write each line.
回答1:
You can also obtain the output directly from QProcess
QProcess process;
process.start(/* command line stuff */);
process.waitForFinished(-1); // will wait forever until finished
QString stdout = process.readAllStandardOutput();
QString stderr = process.readAllStandardError();
If you don't want to block your event loop, you can always use the signals:
readyReadStandardOutput();
readyReadStandardError();
And then call a function to readAllStandard[Output/Error]
回答2:
What you want to execute is a shell command. You need to pass it to a shell. Run the following command using QProcess:
/bin/bash -c "your_command | with_pipes > and_redirects"
回答3:
I just made a C++ class for that. It's part of QDirStat, but it can easily be used standalone:
https://github.com/shundhammer/qdirstat/blob/master/src/OutputWindow.h
and the other files here that this web forum won't let me link to:
- OutputWindow.cpp
- output-window.ui (Qt designer description file)
Screenshot:
https://github.com/shundhammer/qdirstat/blob/master/screenshots/QDirStat-cleanup-output.png
As you can see, it even comes with zoom in / out buttons. You can configure it to show up only if there is output on stderr, to close it when it's done, or to open it only if it takes longer than a (configurable) timeout.
The license is GPL V2. If you are writing an Open Source program, feel free to use it in your application.
来源:https://stackoverflow.com/questions/19409940/how-to-get-output-system-command-in-qt