模拟Python的内置打印功能 [英] Mock Python's built in print function
问题描述
我尝试过
from mock import Mock
import __builtin__
__builtin__.print = Mock()
但这会引发语法错误.我也尝试过像这样修补补丁
But that raises a syntax error. I've also tried patching it like so
@patch('__builtin__.print')
def test_something_that_performs_lots_of_prints(self, mock_print):
# assert stuff
有没有办法做到这一点?
Is there any way to do this?
推荐答案
print
是python 2.x中的关键字,将其用作属性会引发SyntaxError.您可以通过在文件开头使用from __future__ import print_function
来避免这种情况.
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.
注意:您不能简单地使用setattr
,因为除非禁用print
语句,否则不会调用您修改的打印功能.
Note: you can't simply use setattr
, because the print function you modified doesn't get invoked unless the print
statement is disabled.
您还需要在每个要使用修改后的print
函数的文件中from __future__ import print_function
,否则它将被print
语句屏蔽.
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.
这篇关于模拟Python的内置打印功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!