Tinyden
Tinyden

Reputation: 574

How to get environment variable in python subprocess

I have a driver program which launches and manages hundreds of processes by

p = subprocess.Popen(cmd)

One of the situation I'm facing with is: since many processes may set-up their own environment variable by

os.environ[key] = val

which may disappear after the process exits.

My question is: since some of them may fail, I want to reproduce them locally, so I need the environment variables for the correct if-else path.

Is there a way in python to get env vars from subprocess?

Upvotes: 1

Views: 228

Answers (1)

Kurtis Rader
Kurtis Rader

Reputation: 7459

which may disappear after the process exits

That should be "which will disappear". In the UNIX process model env vars are private to each process. If you're on Linux you might be tempted to try reading /proc/$pid/environ. That however would be incorrect since it only lists the vars that were present when the process was created. It will not include any changes the process made to its own env vars.

In short there is no way to do what you want without the explicit cooperation of the child process.

Upvotes: 1

Related Questions