简体   繁体   中英

Python ASTEVAL. How can i capture stdout

I consider using asteval python package for my personal web app.

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.

The issue I faced is that I couldn't obtain stdout of 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.

You can pass in a file object ( writer ) to the Interpreter() class:

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

writer defaults to sys.stdout if you don't specify it, and set when Interpreter() is instantiated. This is why replacing sys.stdout doesn't work; 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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