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
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__
sys.stdout = sys.stderr = os.devnull
. –
Emplace import sys import os print("hello world") sys.stdout = sys.stderr = os.devnull print("hello world")
–
Stroganoff 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
I found this answer and this gist to be really helpful.
E.g. you can just write a small custom context manager to temporarily surpress the
import message of a package
How to suppress the import message:
with suppress_stdout_stderr():
import library_with_import_message
The contextmanager:
# Via Stack Overflow
# https://mcmap.net/q/325042/-suppress-stdout-stderr-print-from-python-functions
# Via gist https://gist.github.com/vikjam/755930297430091d8d8df70ac89ea9e2
import os
from contextlib import contextmanager, redirect_stderr, redirect_stdout
@contextmanager
def suppress_stdout_stderr():
"""A context manager that redirects stdout and stderr to devnull"""
with open(os.devnull, 'w') as fnull:
with redirect_stderr(fnull) as err, redirect_stdout(fnull) as out:
yield (err, out)
© 2022 - 2024 — McMap. All rights reserved.