[英]suppress output on library import in python
我有一個需要在代碼中導入的庫。 但是,無論何時導入,它都會向控制台輸出幾行數據。 我怎樣才能抑制輸出?
謝謝
import os
import sys
# silence command-line output temporarily
sys.stdout, sys.stderr = os.devnull, os.devnull
# import the desired library
import library
# unsilence command-line output
sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
您可以嘗試將 sys.stdout 重定向到 StringIO 以捕獲任何文本輸出。 所以基本上所有打印出來的東西都會保存在 text_trap 中。
import io
import sys
#setup text trap
text_trap = io.StringIO()
sys.stdout = text_trap
#to reset the text trap
sys.stdout = sys.__stdout__
一個工作示例:
from io import BytesIO as StringIO
import sys
if __name__ == "__main__":
print "hello1"
#setup text trap
text_trap = StringIO()
sys.stdout = text_trap
print("hello2")
#reset
sys.stdout = sys.__stdout__
print "hello3"
輸出:
hello1
hello3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.