As mentioned in the comments, you should return
the value(s) from the helper script. If there is more than one, stick it in a list or dictionary (namedtuple
is handy for this).
The key is that you need to assign the result of execfile
to a variable in the server script. This doesn't have to be anything major, it can just be dumped straight into a collection such as a list.
Return-based code
Main file
class Stuff():
def __init__(self, f):
self.f = f
self.log = {}
self.storage = []
def execute(self, filename):
self.storage.append(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)
Helper file (helper.py)
a = 3
b = 4
return (a, b)
Stdout alternative
An alternative approach would be to have the helper file print the results but redirect stdout
. This is fairly trivial if you are using subprocess
and is well detailed in the documentation (I can add an example if it would be beneficial). I'm less familiar with the exec / execfile
approach than subprocess
but there is an explanation on this SO question.
In case anything happens to the other SO question, copied here is the code for the two examples:
Frédéric Hamidi
code = """
i = [0,1,2]
for j in i :
print j
"""
from cStringIO import StringIO
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
exec(code)
sys.stdout = old_stdout
print redirected_output.getvalue()
Jochen Ritzel
import sys
import StringIO
import contextlib
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO.StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
code = """
i = [0,1,2]
for j in i :
print j
"""
with stdoutIO() as s:
exec code
print "out:", s.getvalue()