Suppress stdout / stderr print from Python functions

前端 未结 9 1900
情歌与酒
情歌与酒 2020-11-29 06:59

I have a Python script that is using some closed-box Python functions (i.e. I can\'t edit these functions) provided by my employer. When I call these functions, they are pri

9条回答
  •  情书的邮戳
    2020-11-29 07:32

    Did you try to redirect stderr too? e.g.

    sys.stdout = StringIO()
    sys.stderr = StringIO()
    foo(bar)
    sys.stdout = sys.__stdout__ # These are provided by python
    sys.stderr = sys.__stderr__
    

    Also using StringIO might use extra memory. You can use a dummy device instead (e.g. http://coreygoldberg.blogspot.com/2009/05/python-redirect-or-turn-off-stdout-and.html).

提交回复
热议问题