Skip to content
Advertisement

Retain environment of helper python script in main script

I’ve one helper script which I want to call from main script which is acting as a Server. This main script looks like this:

Class Stuff():
    def __init__(self, f):
        self.f = f
        self.log = {}

    def execute(self, filename):
        execfile(filename)

if __name__ == '__main__':
    #start this script as server
    clazz = Stuff()
    #here helper_script name will be provided by client at runtime
    clazz.execute(helper_script)

Now Client will invoke this helper script by providing it’s name to main script(Server). After execution I want to retain variables of helper script (i.e: a,b) in main script. I know one way is to return those variables from helper script to main script. But is there any other way so to retain all variables of helper script. This is how helper script looks like:

import os
a = 3
b = 4

I tried using execfile and subprocess.

Advertisement

Answer

You can pass a locals dictionary to execfile. After executing the file, this dictionary will contain the local variables it defined.

class Stuff():
    def __init__(self):
        self.log = {}

    def execute(self, filename):
        client_locals = {}
        execfile(filename, globals(), client_locals)
        return client_locals

if __name__ == '__main__':
    #start this script as server
    clazz = Stuff()
    #here helper_script name will be provided by client at runtime
    client_locals = clazz.execute('client.py')
    print(client_locals)

With your client.py, this will print:

{'a': 3, 'b': 4, 'os': <module 'os' from '/Users/.../.pyenv/versions/2.7.6/lib/python2.7/os.pyc'>}

A word of warning on execfile: don’t use it with files from untrusted sources.

Advertisement