Re: Modifying the interpreter's environment

Guido.van.Rossum@cwi.nl
Wed, 14 Sep 1994 23:30:06 +0200

> I need to set certain environment variables before making system and
> popen calls. After reading the manual and FAQ, it's not clear to me
> how this is accomplished. For the system calls, I realize it
> wouldn't be terribly difficult to write a function that forks and
> execve's, but I can't figure a way to make popen work this way.
> Therefore, I think I still need to modify the environment of the
> running python script? Can someone tell me how to do this?

Modifying the environment passed to subshells was left out of the
interpreter because there seemed to be no well-established portable
way to do it.

However if all you want is to pass environment variables to the
commands run by os.system() or os.popen(), there's a simple solution:
prefix the command string with a couple of variable assignments and
export statements. I guess the following would be universal for popen
(untested):

import os
from commands import mkarg # nifty routine to add shell quoting
def epopen(cmd, mode, env = {}):
# env is a dictionary of environment variables
prefix = ''
for key, value in env.values():
prefix = prefix + '%s=%s\n' % (key, mkarg(value))
prefix = prefix + 'export %s\n' % key
return os.popen(prefix + cmd, mode)

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
<URL:http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>