Ways to execute system commands in qt program without opening console window - c++

I am running system() to move files in qt. This leads to blinking of console windows, Is there any way to stop the opening and closing (blinking) of console windows or any alternative ways for system() to hide console windows.
buffer = QString("move \"%2\\*.ico\" \"%2\\%1\" 2>nul")
.arg(images).arg(dir);
qPrintable(buffer);
system(qPrintable(buffer));
buffer = QString("move \"%2\\*.jpg\" \"%2\\%1\" 2>nul")
.arg(images).arg(dir);
system(qPrintable(buffer));
buffer = QString("move \"%2\\*.jpeg\" \"%2\\%1\" 2>nul")
.arg(images).arg(dir);
system(qPrintable(buffer));
buffer = QString("move \"%2\\*.png\" \"%2\\%1\" 2>nul")
.arg(images).arg(dir);
system(qPrintable(buffer));
Here %2 is directory and %1 is inputted folder name.

One option is to use QProcess to run external commands.
Example:
QString program = "move";
QStringList args;
args << QString("\"%1\\*.ico\"").arg(dir);
args << QString("\"%1\\%2\"").arg(dir).arg(images);
QProcess::execute(program, args);

Related

Running a Bash Script with arguments as a Qt resource

Qt newbie here :).
I'm currently executing a bash script in Qt using the popen function to redirect the output to a textBrowser in my application. When I add the script to my project as a resource it does not seem to execute anymore? I use the :/myScript.sh syntax and then try to add my arguments as QStrings.
Any advice will be appreciated!
FILE *in;
char buff[512];
QString args = ":/myScript.sh" + <arguments>;
QByteArray ba = args.toLatin1();
char *temp = ba.data();
if(!(in = popen(temp , "r")))
{
exit(1);
}
while(fgets(buff, sizeof(buff), in)!=NULL)
{
ui->txtConsole->append(buff);
}
ui->progressBar->setValue(50); pclose(in);
Invoking popen with the Qt resource path format will not do what you expect.
You are effectively trying to invoke is this:
popen(":/myScript.sh args", "r");
The popen function doesn't know anything about the Qt resource system nor the :/ syntax. It expects the first parameter to a path on disk that the operating system understands.
Two choices:
Just ship the myScript.sh file as a separate file and execute it directly. (What you observed as working before you tried to make the script a resource). If you aren't using compiled resources, chances are it already is a disk file. Just invoke popen on the absolute path to the file instead of with the :/ syntax.
Write code to extract the myScript.sh text file from the resources and save it locally to disk. Then invoke popen on that saved file.
Its running script file as a qt resource. You add arguments maybe this run.
QStringList arg("-c");
QFile file(":/scriptFile.sh");
arg << file.readAll();
process->start("sh", arg);

Handle different application using C++

Is there any way to control other windows application using c++/qt?
I have: 1000 files of specific image format and an application that can open them. This application can use "Save as..." function to save these files in ".JPEG" format one by one. I want to do this automatically.
Is there any technique to do this? Thank you in advance!
Using QT you have the possibility to run a separate process using a QProcess instance.
Specifically suppose that your external application accepts input parameters (e.g. the filepath to load and the filepath where to store the result.
QProcess shell;
QStringList argv;
//[setup argument-list]
shell.setProcessChannelMode(QProcess::MergedChannels);
shell.start(commandPath, argv);
shell.waitForFinished();
Notice that QProcess can be uses as an IO stream. This is useful to interact with the process (e.g. to retrieve progress information):
shell.start(commandPath, argv);
shell.waitForReadyRead();
while(shell.state() == QProcess::Running || !shell.atEnd()){
auto s = shell.readLine()
//[do something with the current line of the process output]
}
QProcess::ExitStatus es = shell.exitStatus () ;
Of course the external process must accept input parameters and provide feedback through its standard output to solve your problem.

Read output of linux command without using temp file

I need to read input of some linux commands to a QString variable. At first, I redirect the stream to a temp file and read from it.
However, I don't like this way. I want to avoid access the hard drive, the less the better.
I try to use the environment variable as the "temp file", then use getenv to get it into a variable.
like this:
QString query="a=$(fdisk -l)";
system(a.toStdString().c_str());
...
char* env;
env= getenv ("a");
however, I get nothing. Add export to the query has the same result.
I manually check the variables by env command. Nothing changed!
So how to fix this? And are there any better way to do this?
Any ideas are appreciated :)
PS: I want to keep the format too, it should keep \t, \n...
If you are using Qt then you should make it in a Qt's fashion, by utilizing QProcess class.
#include <QProcess>
QString command = "/usr/bin/fdisk";
QStringList arguments;
arguments << "-l";
QProcess process;
process.start(command, arguments);
process.waitForFinished(-1);
QByteArray rawOutput = process.readAllStandardOutput();
QStringList output = QString(rawOutput).split("\n");
foreach (QString line, output)
{
// do something with each line from output
}
It cannot work as you wish, because system or popen will start using fork its own shell process, and the a variable is not exported, and even if it was, it will be available only in that shell process and not in the invoking original process.
Remember that changes in child processes cannot affect their parent process in general (except by using some explicit IPC such as pipes between the two).
The only way you could do what your want is to use popen (or some QProcess specific mechanism to read on pipe the stdout of the child command) on fdisk -l then (if you absolutely want to have your getenv later working) use putenv to set your environment variable.
BTW, fdisk is probably using /proc to get its information (which you could get directly, see proc(5) ...).
Read Advanced Linux Programming, and about fork(2) and execve(2)

Launch console application which uses environment variables from QT Gui application

I am currently making a GUI using QT4.8 which basically needs to launch a console application. However, because this console application tries to fetch some environment variables, I can't seem to manage to make this work.
I am using QProcess obviously and have tried several solutions :
process->start("./yarpbridge", QStringList() << "--from" << "tmp.ini");
This solution does not spawn a console window and besides, by redirecting the output to qDebug(), it prints the erros corresponding to the lack of environment variables.
process->start("gnome-terminal", QStringList() << "-e" << "zsh" << "-c" << "\"./yarpbridge --from tmp.ini"\");
This solution does launch a console window but it nevertheless displays the error messages because somehow .zshrc was probably not consulted when opening the console window.
Would you have a solution that would allow me to do this, and even better that would not only work with "gnome-terminal" and "zsh" users ?
Thanks a lot,
Can you post the error you are getting?
It is very strange because you don't need to start a terminal in order to run a CLI program, maybe after posting your error message I might get an idea what the problem is.
Also you can try this as well:
#include <stdio.h>
char buffer[1024];
FILE* fd = popen("/path/to/yarpbridge", "r");
if (fd == NULL) {
// Error: do something
}
while(NULL != fgets(buffer, sizeof(buffer), fd)) {
QString s(buffer);
s = s.stripWhiteSpace();
// s contains the output, pretty much as readAllStandardOutput() in QProcess
}
// don't forget to close file.
close (fd);

How to use the bash command 'which' from QProcess

I'm a student programmer using Qt and I seem to have ran into an issue using QProcess to launch the bash command 'which' in an attempt to collect a map of installations of an application. I have the following code and I'm truly lost as to what I might be missing. I have referenced the QProcess documentation and still cant figure out whats wrong.
Every time this code is ran the file is not created in the indicated directory. Without the file constructed the application cannot proceed.
//datatypes
QProcess *findFiles = new QProcess();
QStringList arguments;
QStringList InstallationList;
QString program = "/bin/bash";
QString currentUsersHomeDirectory = QDir::homePath();
QString tmpScriptLocation = currentUsersHomeDirectory;
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
//generate file with list of files found
tmpScriptLocation += ".whichBAScriptOutput";
arguments << QString(QString("which -a certainFile >> ") += tmpScriptLocation);
findFiles->setProcessEnvironment(env);
findFiles->start(program,arguments);
findFiles->waitForFinished();
which is located on /usr/bin/ so try to change the path..
EDIT:
You need to connect QProcess's signal readyReadStandardOutput() to your slot. Actually if you take a look at the documentation QProcess inherits from QIODevice. This means you can do something like:
while(canReadLine()){
string line = readLine();
...
}
if you have already written a client-server application in Qt, i am sure you reconized the pseudocode..
As you say you want to execute which, but you are lauching bash with a handwritten script. There is a much easier way to do this in a sequential manner:
//preparing the job,
QProcess process;
QString processName = "which"; //or absoute path if not in path
QStringList arguments = QStringList() << "-a"
<< "certainFile.txt";
// process.setWorkingDirectory() //if you want it to execute in a specific directory
//start the process
process.start(processName, arguments );
//sit back and wait
process.waitForStarted(); //blocking, return bool
process.waitForFinished(); //blocking, return bool
if(process.exitCode() != 0){
//Something went wrong
}
//return a byte array containing what the command "which" print in console
QByteArray processOutput = process.readAll();