天天看點

Python print()重定向 不輸出到螢幕

有這樣一個需求:

如果一個函數

handle_data()

其内部有調用

print()

直接輸出資料到螢幕,但是在某次調用

handle_data()

時又希望其不輸出到螢幕,可以使用裝飾器來進行處理。

具體實作代碼如下:

import os
import sys

def print_redict_wrapper(input_func):
    def wrapper(data):
        with open('temp.dat', 'w') as dest_file:
            old_out = sys.stdout  # 儲存之前的輸出位置
            sys.stdout = dest_file  # 設定目前輸出到檔案
            input_func(data)
            sys.stdout = old_out  # 花園之前的輸出位置

    return wrapper

# 這裡不使用@ print_redict_wrapper
# 是希望直接調用handle_data()時還是輸出到螢幕
def handle_data(data):
    print(data)

if __name__ == '__main__':
    handle_data('hellohi before')
    # 下面調用handle_data希望不輸出到螢幕
    # 使用print_redict_wrapper進行包裝
    wrapper_func = print_redict_wrapper(handle_data)
    wrapper_func('hellohi')
    handle_data('hellohi after')
           

代碼輸出為:

hellohi before
hellohi after
           

生成的臨時檔案

temp.dat

也可以将其删除。