简体   繁体   English

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

[英]Python ASTEVAL. How can i capture stdout

I consider using asteval python package for my personal web app. 我考虑将asteval python软件包用于我的个人Web应用程序。

ASTEVAL is a safe(ish) evaluator of Python expressions and statements, using Python's ast module. 使用Python的ast模块,ASTEVAL是Python表达式和语句的安全(ish)评估器。 The idea is to provide a simple, safe, and robust miniature mathematical language that can handle user-input. 想法是提供一种可以处理用户输入的简单,安全和健壮的微型数学语言。

The issue I faced is that I couldn't obtain stdout of asteval. 我面临的问题是我无法获得asteval标准。 I tried to capture it using the following snippet: 我尝试使用以下代码段捕获它:

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

and then: 接着:

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

but no luck, output is an empty list. 但没有运气, output是一个空列表。

You can pass in a file object ( writer ) to the Interpreter() class: 您可以将文件对象( writer )传递给Interpreter()类:

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

writer defaults to sys.stdout if you don't specify it, and set when Interpreter() is instantiated. 如果未指定, writer默认为sys.stdout ,并在实例化Interpreter()时设置。 This is why replacing sys.stdout doesn't work; 这就是为什么替换sys.stdout不起作用的原因。 the instance already has their own reference to it. 该实例已经有自己的引用。

Demo: 演示:

>>> 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