Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter out warning info

Tags:

python

My code imports a function(import_function) from the other module(written by other guys).

ret = import_function(arg1,arg2)

The function will PRINT some warning info when it runs(the function uses print() to display the warning messages). The question is: how can I filter out all these warning info?

I have tried the following way, but it doesn't work.

console_redirect = sys.stdout
sys.stdout = os.devnull
ret = import_function(arg1,arg2)
sys.stdout = console_redirect
like image 314
Matt Elson Avatar asked Jan 18 '26 01:01

Matt Elson


1 Answers

I think the issue with with sample code you provided is that os.devnull is a string; not a file object. You need to wrap it in an open(). Like this:

sys.stderr = open(os.devnull, 'w')
ret = import_function(arg1,arg2)
sys.stderr = sys.__stderr__

there is no need to backup the original stdios, they are retained in sys.__stdin__, sys.__stdout__ and sys.__syserr__

If you are sure the output is coming out on stdout (via the print statement) replace stderr with stdout.

like image 139
tMC Avatar answered Jan 19 '26 14:01

tMC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!