如何使 print() 覆盖“全局"工作 [英] How to make print() override work "globally"

查看:54
本文介绍了如何使 print() 覆盖“全局"工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 如何使用导入语句覆盖 python 内置函数 我得到以下代码:

From How to override python builtins with an import statement I obtained the following code:

from __future__ import print_function
def print(*args, **kwargs):
    .
    . some intervening logic
    .
    return __builtins__.print(*args, **kwargs)

此代码工作正常,但具有模块范围.也就是说,如果这个文件中有打印语句,它们会按预期工作,按照定义的方式执行打印()函数.但是,导入它(from foo import *)在导入它的模块中无效.

This code works fine, but has module scope. That is, if there are print statements within this file they work as expected, going through the print() function as defined. However, importing it (from foo import *) has no effect within the module that imported it.

如果我想全局"覆盖打印功能,最好怎么做.理想情况下:

If I want to override the print function "globally" how is this best done. Ideally:

from MyOverrides import *
.
.
.
class foo():
    .
    .
    def bar( self ):
        print( "this is my overridden print statement" )

我对 future、覆盖和 print() 遗漏了什么?

What am I missing about future, overrides, and print() here?

我的环境是 2.6 及更高版本,但不是 3.0.

My environment is 2.6 and forward, but not 3.0.

推荐答案

另一个 stackoverflow 用户提供了大部分答案,但随后显然将其删除 (?).这是一个有效的解决方案.再说一次,我承认这不一定是最佳做法,但在某些情况下可能会很方便.

Another stackoverflow user provided most of the answer, but then apparently deleted it (?). Here is a working solution. Once again, I recognize this isn't necessarily a best practice, but it can be handy in certain situations.

模块 MyOverrides.py:

Module MyOverrides.py:

from __future__ import print_function
import __builtin__

builtin_print = __builtin__.print
def print(*args, **kwargs):
    .
    .... whatever code you need here
    .
    return builtin_print(*args, **kwargs)
__builtin__.print = print

模块 test.py:

Module test.py:

from __future__ import print_function
from MyOverrides import *
.
.
.

正如另一位用户所指出的,未来导入需要在每个打算使用未来功能的模块中进行.

As pointed out by another user, future import needs to happen in every module that intends to use future functionality.

感谢用户@kindall 回答,然后显然撤回了答案.

Thanks to user @kindall who answered and then apparently withdrew the answer.

这篇关于如何使 print() 覆盖“全局"工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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