How can I import the enviroment variables of a completed process in python?
I need to write a python script that la开发者_如何学Gounches 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?
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.
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.
精彩评论