Skip to content

Commit

Permalink
Merge pull request #22 from sarthhh/rewrite
Browse files Browse the repository at this point in the history
fix the eval command
  • Loading branch information
externref authored Dec 24, 2022
2 parents af33540 + 2a7a07c commit 7db06a0
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions wyvern/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@
from __future__ import annotations

import ast
import contextlib
import datetime
import inspect
import io
import typing

import attrs
Expand Down Expand Up @@ -166,8 +168,14 @@ async def f_eval(self, *, code: str, renv: dict[str, typing.Any]) -> typing.Any:
"""
_fn_name = "__wyvern_eval"
code = "\n".join(f" {i}" for i in code.strip().splitlines())
parsed: typing.Any = ast.parse(f"async def {_fn_name}:\n{code}")
self.add_returns(parsed.body[0].body)
exec(compile(parsed, filename="<ast>", mode="exec"), renv)
fn = renv[_fn_name]
return await fn()
stdout, stderr = io.StringIO(), io.StringIO()
try:
parsed: typing.Any = ast.parse(f"async def {_fn_name}():\n{code}")
self.add_returns(parsed.body[0].body)
exec(compile(parsed, filename="<ast>", mode="exec"), renv)
fn = renv[_fn_name]
with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
await fn()
except Exception as e:
return stdout.getvalue(), stderr.getvalue() + f"{type(e).__name__}: {e}"
return stdout.getvalue(), stderr.getvalue()

0 comments on commit 7db06a0

Please sign in to comment.