問題描述
我試過了
from mock import Mock
import __builtin__
__builtin__.print = Mock()
但這會引發(fā)語法錯誤.我也試過這樣修補(bǔ)它
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
有沒有辦法做到這一點(diǎn)?
Is there any way to do this?
推薦答案
print
是 python 2.x 中的關(guān)鍵字,將其用作屬性會引發(fā) 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
,因?yàn)槟阈薷牡拇蛴『瘮?shù)不會被調(diào)用,除非 print
語句被禁用.
Note: you can't simply use setattr
, because the print function you modified doesn't get invoked unless the print
statement is disabled.
您還需要 from __future__ import print_function
在您希望使用修改后的 print
函數(shù)的每個文件中,否則它將被 打印
語句.
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.
這篇關(guān)于模擬 Python 的內(nèi)置打印功能的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!