Mock Python's built in print function

前端 未结 11 2008
醉话见心
醉话见心 2020-12-06 09:10

I\'ve tried

from mock import Mock
import __builtin__

__builtin__.print = Mock()

But that raises a syntax error. I\'ve also tried patching

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 09:43

    print is a keyword in python 2.x, using it as attribute raises a SyntaxError. You can avoid that by using from __future__ import print_function in the beginning of the file.

    Note: you can't simply use setattr, because the print function you modified doesn't get invoked unless the print statement is disabled.

    Edit: you also need to from __future__ import print_function in every file you want your modified print function to be used, or it will be masked by the print statement.

提交回复
热议问题