Search code examples
c++qtshellqtguiqtcore

Qt Windows application to open console output


I have a Windows application that I want to run some ant scripts from the console/command line. What I would like to do is click on my execute button and open a console/shell window and run the command on windows, unix, mac and exit when its done. This way I can see all the output. I've been using QProcess to do it and it works. But I really want to open a console window every time I run the script. Is their an API that I can use to do this?

Update

Here is my code:

QString argument = QString("ant -f %1 %2 %3\n\r").arg(QDir::cleanPath(file), parameter, target);
QProcess scriptProcess;
scriptProcess.setProcessChannelMode(QProcess::MergedChannels);

if (Commons::GetCurrentOSID() == 1) // Windows
    scriptProcess.start(QString("cmd"));
else if (Commons::GetCurrentOSID() == 2) // Mac
    scriptProcess.start(QString("bash"));
else if (Commons::GetCurrentOSID() == 3)
    scriptProcess.start(QString("bash")); // Windows

if (!scriptProcess.waitForStarted())
{
    message.append("Ant command failed to execute");
}
else
{
    scriptProcess.write(argument.toStdString().c_str());
    scriptProcess.write("exit\n\r");

    result = scriptProcess.waitForFinished();
    if (result == false)
    {
        message.append("Ant command failed to complete");
    }
    else
        result = true;
}

scriptProcess.closeWriteChannel();
QByteArray output = scriptProcess.readAll();
text->setPlainText(output);

Note: Make sure you have your ant, java, etc settings set in the environment.


Solution

  • This is the code I would personally use:

    QProcess scriptProcess;
    scriptProcess.setProcessChannelMode(QProcess::MergedChannels);
    scriptProcess.start("ant", QStringList{"-f", "build.xml", "-Dproject=something"});
    if (!scriptProcess.waitForStarted())
        return false;
    
    if (!scriptProcess.waitForFinished())
        return false;
    
    QByteArray output = scriptProcess.readAll();
    myLabel.setText(output);
    

    Make sure you use shebang and so on properly, otherwise, you might need to specify the interpreter explicitly.