第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從Python函數(shù)調(diào)用中捕獲stdout輸出?

如何從Python函數(shù)調(diào)用中捕獲stdout輸出?

慕碼人8056858 2019-08-31 14:44:56
我正在使用一個對象做某事的Python庫do_something(my_object)并改變它。這樣做時,它會向stdout打印一些統(tǒng)計信息,我想抓住這些信息。適當?shù)慕鉀Q方案是改變do_something()以返回相關信息,out = do_something(my_object)但在開始討論do_something()這個問題之前還需要一段時間。作為一種解決方法,我考慮解析do_something()對stdout的任何寫入。如何在代碼中的兩點之間捕獲stdout輸出,例如,start_capturing()do_something(my_object)out = end_capturing()?
查看完整描述

2 回答

?
慕哥9229398

TA貢獻1877條經(jīng)驗 獲得超6個贊

試試這個上下文管理器


# import StringIO for Python 2 or 3

try:

    from StringIO import StringIO

except ImportError:

    from io 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())

        del self._stringio    # free up some memory

        sys.stdout = self._stdout

用法:


with Capturing() as output:

    do_something(my_object)

output 現(xiàn)在是一個包含函數(shù)調(diào)用打印的行的列表。


高級用法:


可能不明顯的是,這可以不止一次完成并且結(jié)果連接起來:


with Capturing() as output:

    print 'hello world'


print 'displays on screen'


with Capturing(output) as output:  # note the constructor argument

    print 'hello world2'


print 'done'

print 'output:', output

輸出:


displays on screen                     

done                                   

output: ['hello world', 'hello world2']

更新:他們還說redirect_stdout()到contextlib在Python 3.4(沿redirect_stderr())。因此,您可以使用io.StringIO它來實現(xiàn)類似的結(jié)果(盡管Capturing列表以及上下文管理器可以說更方便)。


查看完整回答
反對 回復 2019-08-31
?
尚方寶劍之說

TA貢獻1788條經(jīng)驗 獲得超4個贊

在python> = 3.4中,contextlib包含一個redirect_stdout裝飾器。它可以用來回答你的問題:


import io

from contextlib import redirect_stdout


f = io.StringIO()

with redirect_stdout(f):

    do_something(my_object)

out = f.getvalue()

來自文檔:


用于臨時將sys.stdout重定向到另一個文件或類文件對象的上下文管理器。


此工具為輸出硬連線到stdout的現(xiàn)有函數(shù)或類增加了靈活性。


例如,help()的輸出通常發(fā)送到sys.stdout。您可以通過將輸出重定向到io.StringIO對象來捕獲字符串中的輸出:


  f = io.StringIO() 

  with redirect_stdout(f):

      help(pow) 

  s = f.getvalue()

要將help()的輸出發(fā)送到磁盤上的文件,請將輸出重定向到常規(guī)文件:


 with open('help.txt', 'w') as f:

     with redirect_stdout(f):

         help(pow)

要將help()的輸出發(fā)送到sys.stderr:


with redirect_stdout(sys.stderr):

    help(pow)

請注意,sys.stdout的全局副作用意味著此上下文管理器不適合在庫代碼和大多數(shù)線程應用程序中使用。它對子進程的輸出也沒有影響。但是,它仍然是許多實用程序腳本的有用方法。


此上下文管理器是可重入的。


查看完整回答
反對 回復 2019-08-31
  • 2 回答
  • 0 關注
  • 1012 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號