开发者

How to filter out warning info

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜