You don't need to create a tempfile, you can simply use exec
. create_decision
would then look so:
A
def create_decision(user_decision, conditions):
f = open(conditions, 'r+')
contents = f.readlines()
contents.append(user_decision)
# join list entries with a newline between and return result as string
output = eval('\n'.join(contents))
return output
B
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
def create_decision(user_decision, conditions):
f = open(conditions, 'r+')
contents = f.readlines()
contents.append(user_decision)
with stdoutIO() as output:
#exec('\n'.join(contents)) # Python 3
exec '\n'.join(contents) # Python 2
return output.getvalue()
You should also use str.join()
to make one string out of the list of conditions. Otherwise you couldn't write it to a file or execute it (I've done this already in the above function).
Edit: There was a bug in my code (exec
doesn't return anything) so I've added a method with eval
(but that won't work with print, because it evaluates and returns the result of one expression, more info here). The second method captures the output of print
and stdoutIO
is from an other question/answer (here). This method returns the output from print, but is a bit more complicated.