views:

27

answers:

2

I need to write a python script that launches a shell script and import the environment variables AFTER a script is completed.

Immagine you have a shell script "a.sh":

export MYVAR="test"

In python I would like to do something like:

import os
env={}
os.spawnlpe(os.P_WAIT,'sh', 'sh', 'a.sh',env)
print env

and get:

{'MYVAR'="test"}

Is that possible?

+5  A: 

Nope, any changes made to environment variables in a subprocess stay in that subprocess. (As far as I know, that is) When the subprocess terminates, its environment is lost.

I'd suggest getting the shell script to print its environment, or at least the variables you care about, to its standard output (or standard error, or it could write them to a file), and you can read that output from Python.

David Zaslavsky
This is probably the best way to do it. However, one suggestion I'd add is that if it isn't possible to modify the shell script defining the values, you could change your command to `bash -c '. <env_setting_script>; env'` Essentially, your subshell sources the environment then prints it out itself rather than having the script do it directly.
Rakis
A: 

I agree with David's post.

Perl has a Shell::Source module which does this. It works by running the script you want in a subprocess appended with an env which produces a list of variable value pairs separated by an = symbol. You can parse this and "import" the environment into your process. The module is worth looking at if you need this kind of behaviour.

Noufal Ibrahim