From: arcege at shore.net (Michael P. Reilly)
Date: Wed, 28 Apr 1999 15:57:28 GMT
Subject: 'sourcing' Python scripts?
References: <372713AD.6ABA444@cern.ch>
Message-ID: <IdGV2.129$pX2.73964@news.shore.net>
Content-Length: 1394
X-UID: 872                                                  

Haimo G. Zobernig <Haimo.Zobernig at cern.ch> wrote:
: Dear Python experts,

: this might be a unix rather than a Python problem, but I need to set
: environment variables from a Python program *in the parent process* 
: that is running the Python script ( a la os.environ['BAR'] = 'foo' ).
: In other words, I want to achieve the equivalent of 'sourcing' the 
: Python script. Can this be done? Even better would be a solution that
: also works on the various WinAbominations... (well, NT at least)

: Haimo G. Zobernig

: Haimo.Zobernig at cern.ch

Are both programs written in Python?

If so, then you could make something like:

  def environ_save(filename, environ):
    file = open(filename, 'w')
    lines = [ 'environ = {}\n' ]
    for (key, value) in environ.items():
      lines.append('environ[%s] = %s\n' % (repr(key), repr(value)))
    open(filename, 'w').writelines(lines)

  def environ_load(filename, other_environ):
    execfile(filename)  # this creates a local variable called 'environ'
    for (key, value) in environ.items():
      other_environ[key] = value

Call "environ_save" from the child process, and "environ_load" from the
parent.  Also, this relies on the data being reproducable from repr().
Which, if it is from os.environ, it should be. :)

Now, I haven't tested this, but I don't see any problems.  A pickle
solution can be left to the reader.

  -Arcege





