Pergunta

Good day! I'm trying to implement a module for testing knowledge. The user is given the task, he wrote the decision that is being sent and executed on the server. The question in the following. There are raw data that is stored in the file. Example - a = 5 b = 7 There is a custom solution that is stored in the string. example

s = a * b
p = a + b
print s,p

Now it is all written in a separate file as a string.

'a = 5\n', 'b = 7', u's = a * b\r\np = a + b\r\nprint s,p'

How to do this so that the code used can be performed. Will be something like that.

a = 5
b = 7
s = a * b
p = a + b
print s,p

Here's my function to create a solution and executes it if necessary.

def create_decision(user_decision, conditions):
    f1 = open('temp_decision.py', 'w')
    f = open(conditions, 'r+')
    contents = f.readlines()
    contents.append(user_decision)
    f1.write(str(contents))
    f1.close()
    output = []
    child_stdin, child_stdout, child_stderr = os.popen3("python temp_decision.py")
    output = child_stdout.read()
    return output

Or tell me what I'm doing wrong? Thanks!

Foi útil?

Solução

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.

Outras dicas

You can execute a string like so: exec("code")

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top