I have a library that I need to import on my code. However, whenever it is imported it outputs several lines of data to the console. How can I suppress the output?
Thanks
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__
You can try to redirect sys.stdout into a StringIO to capture any text output. So basically everything which would be printed out, will be saved in 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__
A working example:
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"
Output:
hello1
hello3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.