File: interpreter.py

package info (click to toggle)
freeorion 0.5.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 194,940 kB
  • sloc: cpp: 186,508; python: 40,969; ansic: 1,164; xml: 719; makefile: 32; sh: 7
file content (46 lines) | stat: -rw-r--r-- 1,404 bytes parent folder | download
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
import logging
import sys
from code import InteractiveInterpreter
from io import StringIO

from freeorion_tools.chat_handler.shell_variable import ShellVariable


class DebugInterpreter:
    def __init__(self, shell_locals: list[ShellVariable]):
        self._shell_locals = shell_locals
        self._interpreter = InteractiveInterpreter()

    def eval(self, msg):
        old_stdout = sys.stdout
        old_stderr = sys.stderr

        sys.stdout = StringIO()
        sys.stderr = StringIO()
        if msg.endswith(";"):
            msg = msg.replace(";", "\n")
        handler = logging.StreamHandler(sys.stdout)
        logging.getLogger().addHandler(handler)
        self._interpreter.runsource(msg)
        logging.getLogger().removeHandler(handler)

        sys.stdout.seek(0)
        out = sys.stdout.read()
        sys.stderr.seek(0)
        err = sys.stderr.read()
        sys.stdout = old_stdout
        sys.stderr = old_stderr
        return out.strip("\n"), err.strip("\n")

    def set_locals(self):
        initial_code = []

        variables_description = []
        for shellLocal in self._shell_locals:
            initial_code.extend(shellLocal.get_evaluation_command())
            result = shellLocal.name, shellLocal.description
            variables_description.append(result)
        for line in initial_code:
            self.eval(line)

        return variables_description