簡體   English   中英

在 contextlib.redirect_stdout() 中,print() 函數導致 AttributeError: 'str' object has no attribute 'write'

[英]Within contextlib.redirect_stdout() the print()-function causes an AttributeError: 'str' object has no attribute 'write'

我嘗試按照這篇文章的建議將我的 python 代碼特定部分的整個控制台輸出重定向到一個文本文件。

根據那篇文章,它應該與 contextlib.redirect_stdout() 一起使用,但是我的自定義函數 custom_function_with_internal_print_calls() 中出現第一個 print() 命令時,它會拋出AttributeError: 'str' object has no attribute 'write'

dummy_file = "dummy_textfile.txt"  # file to which the stdout shall be redirected

with contextlib.redirect_stdout(dummy_file):
    # Direct print()-function call
    print("Informative string which shall go to the textfile instead of the console.")

    # Indirect print()-function calls (internally)
    custom_function_with_internal_print_calls(**kwargs)

編輯:在我的特殊情況下,我有一個自定義函數,而不是 with-environment 中的 print() 函數,它具有對 Python 內置 print() 函數的內部調用。 如果 print() 函數出現在另一個函數中,或者直接出現在頂層以重現錯誤,這無關緊要。

已經嘗試過的選項:其他解決方法似乎沒有提供我正在尋找的解決方案,例如

重新定義 print() 函數

為 python 2.7x 編寫裝飾器(因為我使用的是 python 3.7x),或者也

通過print('Filename:', filename, file=f) 將 print() 函數重定向到文件對象 在我的情況下,后者意味着將文件處理程序傳遞給我選擇的封閉函數中的所有子函數,這對於這種特殊情況來說是太多額外的代碼修改。

我希望能夠僅with contextlib.redirect_stdout(dummy_file):環繞我的函數的環境,以便將此函數的每個控制台輸出重定向到dummy_file

contextlib.redirect_stdout()文檔也沒有幫助我。 預先感謝您的建議。

我通過將文件處理程序“f”傳遞給函數contextlib.redirect_stdout(f)而不是文件路徑dummy_file找到了解決方案,如本文所建議

dummy_file = "dummy_textfile.txt"  # file to which the stdout shall be redirected

with open(dummy_file, 'w') as f:
    with contextlib.redirect_stdout(f):
        # Indirect print()-function calls (internally)
        custom_function_with_internal_print_calls(**kwargs)

這樣,所有的 print() 函數調用都會寫入 dummy_file 並在之后恢復標准控制台輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM