File size: 1,065 Bytes
d195d4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import sys
import io
import yaml
import pdb

class python_executor:
    def __init__(self):
        pass

    def run_single(self, program):
        buffer = io.StringIO() # Create an in-memory buffer for the output
        stdout = sys.stdout # Save the original standard output
        sys.stdout = buffer # Redirect the standard output to the buffer
        try:
            exec(program)
        except Exception as e:
            # Handle the error here
            error_message = str(e)
            sys.stdout = stdout  # Restore the original standard output
            return error_message

        exec(program)
        sys.stdout = stdout # Restore the original standard output
        output = buffer.getvalue() # Get the output from the buffer
        return output

    def run(self, snippet):
        if snippet == None:
            return None
        exec_result = self.run_single(snippet)
        if exec_result and 'False' in exec_result:
            exec_result = 'False'
        else:
            exec_result = 'True'
        return exec_result