forked from Archives/langchain
You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
27 lines
816 B
Python
27 lines
816 B
Python
"""Mock Python REPL."""
|
|
import sys
|
|
from io import StringIO
|
|
from typing import Dict, Optional
|
|
|
|
from pydantic import BaseModel, Field
|
|
|
|
|
|
class PythonREPL(BaseModel):
|
|
"""Simulates a standalone Python REPL."""
|
|
|
|
globals: Optional[Dict] = Field(default_factory=dict, alias="_globals")
|
|
locals: Optional[Dict] = Field(default_factory=dict, alias="_locals")
|
|
|
|
def run(self, command: str) -> str:
|
|
"""Run command with own globals/locals and returns anything printed."""
|
|
old_stdout = sys.stdout
|
|
sys.stdout = mystdout = StringIO()
|
|
try:
|
|
exec(command, self.globals, self.locals)
|
|
sys.stdout = old_stdout
|
|
output = mystdout.getvalue()
|
|
except Exception as e:
|
|
sys.stdout = old_stdout
|
|
output = str(e)
|
|
return output
|