我考虑将^{
ASTEVAL is a safe(ish) evaluator of Python expressions and statements, using Python's ast module. The idea is to provide a simple, safe, and robust miniature mathematical language that can handle user-input.
我面临的问题是我无法获得asteval的标准输出。我试着用下面的片段捕捉它:
from asteval import Interpreter
aeval = Interpreter()
from cStringIO import StringIO
import sys
class Capturing(list):
def __enter__(self):
self._stdout = sys.stdout
sys.stdout = self._stringio = StringIO()
return self
def __exit__(self, *args):
self.extend(self._stringio.getvalue().splitlines())
sys.stdout = self._stdout
然后:
^{pr2}$但是运气不好,output
是一个空列表。在
您可以将文件对象(
writer
)传递给Interpreter()
类:如果不指定,
writer
默认为sys.stdout
,并在实例化Interpreter()
时设置。这就是替换sys.stdout
不起作用的原因;实例已经有了自己的引用。在演示:
^{pr2}$相关问题 更多 >
编程相关推荐