模拟Python的内置打印功能 [英] Mock Python's built in print function

查看:79
本文介绍了模拟Python的内置打印功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆