Reputation: 63
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.
Upvotes: 6
Views: 9687
Reputation: 781
another way to accomplish it without parsing external files; in my case i need to execute vcvarsall.bat from different msvc versions, and need to capture the complete environment after calling them (individually):
call ...\vc\vcvarsall.bat call may\be\another.cmd echo {5c131c2a-405b-478a-8279-9dff52c31537} set
QProcess
i use readAllStandardOutput()
to gather all the output.QProcessEnvironment
(as already mentioned), and can apply it to new processes as is or with additional modifications.Upvotes: 0
Reputation: 12247
You can read all environment variables set in the QProcess in a nicer format the following way (to the standard debug output window). It will print each variable in new line.
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
qDebug() << "All variables";
QString env_variable;
QStringList paths_list = env.toStringList();
foreach( env_variable, paths_list )
qDebug() << env_variable;
Upvotes: 1
Reputation: 42474
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
Upvotes: 6
Reputation: 1793
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.
Upvotes: 1