Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve environment variables of a QProcess

Tags:

c++

qt

I want to run an environment script within a QProcess and then read the environment (as a QStringList) to start other scripts with this environment.

If I start the env script and read the environment, I always get an empty QStringList. Is there a way to read out the environment of a QProcess?

I also tried to first start the environment script and the start the actual script on the same QProcess object but that did not help either.

like image 265
Nick Avatar asked Feb 17 '11 18:02

Nick


2 Answers

If you are able to rewrite the script which sets the environment in C++ you can create the environment yourself and set it using
void QProcess::setProcessEnvironment ( const QProcessEnvironment & environment ) method as in the example given in the method's documenation:

 QProcess process;
 QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
 env.insert("TMPDIR", "C:\\MyApp\\temp"); // Add an environment variable
 env.insert("PATH", env.value("Path") + ";C:\\Bin");
 process.setProcessEnvironment(env);
 process.start("myapp");

UPDATE

If you can't use the above method you could try using cmd.exe like this;

#include <QtCore/QCoreApplication>
#include <QtCore/QProcess>

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QProcess* proc = new QProcess();
    proc->start("cmd.exe /c \"call env.bat && script.bat\"");

    return app.exec();
}

Having env.bat with this contents

set abc=test

and script.bat with this contents

echo %abc% > a.txt

running the above creates a.txt file with this contents

test 
like image 128
Piotr Dobrogost Avatar answered Oct 04 '22 20:10

Piotr Dobrogost


If you haven't used QProcess's setEnvironment method, then the empty QStringList is the expected output. For this case, QProcess uses the program's environment. To get this,

QStringList env(QProcess::systemEnvironment());

should work.

like image 41
ctd Avatar answered Oct 04 '22 22:10

ctd