File size: 2,485 Bytes
0078c1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import json
import textwrap


def run_python_code(code: str) -> str:
    """Execute Python code and return output.

    Args:
        code: Python code to execute

    Returns:
        JSON string with stdout, stderr, and result
    """
    stdout_output = []
    stderr_output = []
    result = None
    error = None

    # Capture stdout
    import io
    import sys

    old_stdout = sys.stdout
    old_stderr = sys.stderr
    sys.stdout = io.StringIO()
    sys.stderr = io.StringIO()

    try:
        # Execute the code
        exec_globals = {}
        exec(code.strip(), exec_globals)

        # Get any last expression result (check for common patterns)
        sys.stdout = old_stdout
        sys.stderr = old_stderr

        # Check for printed output
        stdout_text = ""

        # Try to get result from exec
        try:
            # Check for variables that might hold the result
            for var_name in ['result', 'answer', 'output', 'final_answer', 'x']:
                if var_name in exec_globals:
                    result = exec_globals[var_name]
                    break
        except Exception:
            pass

    except Exception as e:
        sys.stdout = old_stdout
        sys.stderr = old_stderr
        error = str(e)
        stdout_text = sys.stdout.getvalue() if hasattr(sys.stdout, 'getvalue') else ""

    sys.stdout = old_stdout
    sys.stderr = old_stderr

    # If we still have no result, try to evaluate the last line
    if result is None and not error:
        lines = code.strip().split('\n')
        for line in reversed(lines):
            stripped = line.strip()
            # Look for print statements or assignments
            if stripped.startswith('print('):
                try:
                    result = eval(stripped[6:-1], {})
                    break
                except Exception:
                    continue
            elif '=' in stripped and not stripped.startswith('#'):
                parts = stripped.split('=', 1)
                if len(parts) == 2:
                    var_name = parts[0].strip()
                    try:
                        result = eval(parts[1].strip(), {})
                        break
                    except Exception:
                        continue

    output = {
        'stdout': stdout_text,
        'stderr': stderr_output,
        'result': str(result) if result is not None else None,
        'error': error,
    }

    return json.dumps(output, indent=2)