python, shell, environment variable

Eric Brunel eric.brunel at pragmadev.com
Tue Jun 11 06:15:28 EDT 2002


oliver wrote:

> hi, folks,
> 
> I am trying to get a set of python and bash scripts to work, and I
> constantly run into trouble with environment variables:
> 
> First, my python script need to modify environment variable, say,
> PATH, and want to keep the modification even after the script is done.
> os.environ["PATH"]= ... doesn't seem to work, any idea?

Modifying environment variables this way is simply impossible: a process 
run by another process cannot change the environment of its parent, so your 
Python script will not be able to change environment variables in a 
persistent way.

> Second, it would be better if my python script can call bash shell and
> still keep the environment variable modification done by bash. I tried
> os.popen("source some_shell"), it doesn't work. ?

Same answer: this is impossible. os.popen runs the command in a subshell, 
and the environment variable changes made by the "source" will only be 
visible in that sub-shell.

One way to achieve what you want to do is to describe the environment 
variables you want to change in a file created by the sub-process. That 
file will then be used by the parent to do the actual variable settings. 
Here is an example:

---------foo.sh---------------------
cat > /tmp/envvars <<.
MYVAR1=value1
MYVAR2=value2
.
------------------------------------

---------foo.py---------------------
import os
os.system('foo.sh')
for l in open('/tmp/envvars').readlines():
  var, val = l.strip().split('=')
  os.environ[var] = val
# ...
print os.environ['MYVAR1']
------------------------------------

This works from a bash child to a Python parent. The reverse is also 
possible using the same mechanism: the Python script may simply create a 
file containing "setenv" commands that will be source'd by the parent bash 
script.

HTH
-- 
- Eric Brunel <eric.brunel at pragmadev.com> -
PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com



More information about the Python-list mailing list