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