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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With