繁体   English   中英

Python ASTEVAL。 我如何捕获标准输出

[英]Python ASTEVAL. How can i capture stdout

我考虑将asteval python软件包用于我的个人Web应用程序。

使用Python的ast模块,ASTEVAL是Python表达式和语句的安全(ish)评估器。 想法是提供一种可以处理用户输入的简单,安全和健壮的微型数学语言。

我面临的问题是我无法获得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

接着:

with Capturing() as output:
    aeval('print "this should be captured"')

但没有运气, output是一个空列表。

您可以将文件对象( writer )传递给Interpreter()类:

output = StringIO()
aeval = Interpreter(writer=output)

如果未指定, writer默认为sys.stdout ,并在实例化Interpreter()时设置。 这就是为什么替换sys.stdout不起作用的原因。 该实例已经有自己的引用。

演示:

>>> from cStringIO import StringIO
>>> from asteval import Interpreter
>>> output = StringIO()
>>> aeval = Interpreter(writer=output)
>>> aeval('print "this should be captured"')
>>> output.getvalue()
'this should be captured\n'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM