Set an environment variable

jepler at jepler at
Thu Oct 20 14:18:57 CEST 2005

In Unix, you generally can't affect the environment of your parent program (in
a broad sense, which includes environment variables, current working directory,
opened files, effective user ID, etc).

You have two basic choices to achieve an effect like this.  First, you can
start a subshell with the desired environment, something like (untested)
	os.environ['VARIABLE'] = 'value'
(commands like 'su' work in this way)

Second, you can produce shell commands that have the effect of changing a
shell's environment when they are executed.  Something like:
	print "VARIABLE=value"
To use this, the user must write something like
	eval ``
instead of just
this can typically be encapsulated in a shell alias or function.
(commands like 'resize' (which sets the shell's idea of a terminal's size) work
this way)

Finally, you might be able to use an OS-specific interface like linux' ptrace
to change the actual contents of a calling process's memory.  I didn't
immediately find an example of this, but on Linux it would consist of using
PTRACE_PEEKDATA and PTRACE_POKEDATA to locate the environment in another
process and modify it.  The ptrace interface is not available from any standard
Python module, and isn't portable anyway. (though my manpage actually says
'CONFORMING TO SVr4, ..., X/OPEN, BSD 4.3' so maybe ptrace is more portable
than I believed)

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <>

More information about the Python-list mailing list