重载打印python

45 python printing overloading

我能够重载该print函数并从内部调用正常函数吗?我想要做的是在我要print调用的特定行之后print调用普通行print并将副本写入文件.

另外我不知道怎么超载print.我不知道如何做变长参数.我很快就会查看,但是 重载打印python告诉我,我不能print2.x中超载,这就是我正在使用的.

Dev*_*yer 59

对于那些审查以前过时的答案的人,从版本发布的"Python 2.6"开始,对原始海报的问题有一个新的答案.

在Python 2.6及更高版本中,您可以禁用print语句以支持print函数,然后使用您自己的print函数覆盖print函数:

from __future__ import print_function
# This must be the first statement before other statements.
# You may only put a quoted or triple quoted string, 
# Python comments, other future statements, or blank lines before the __future__ line.

try:
    import __builtin__
except ImportError:
    # Python 3
    import builtins as __builtin__

def print(*args, **kwargs):
    """My custom print() function."""
    # Adding new arguments to the print function signature 
    # is probably a bad idea.
    # Instead consider testing if custom argument keywords
    # are present in kwargs
    __builtin__.print('My overridden print() function!')
    return __builtin__.print(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

当然,您需要考虑此打印功能此时仅为模块范围.你可以选择覆盖__builtin__.print,但你需要保存原件__builtin__.print; 可能与__builtin__命名空间混淆.

  • 您应该执行`import __builtin__`然后`__builtin __.print`而不是使用`__builtins__`,[请参阅此处的说明](https://docs.python.org/2/reference/executionmodel.html). (2认同)

ʞɔı*_*ɔıu 32

重载print是python 3.0的一个设计特性,以解决你在python 2.x中缺乏这样做的能力.

但是,您可以覆盖sys.stdout.(例如.)只需将其分配给另一个类似文件的对象即可.

或者,您可以通过unix tee命令管理脚本.python yourscript.py | tee output.txt将打印到stdout和output.txt,但这将捕获所有输出.


小智 10

我遇到了同样的问题.

这个怎么样:

class writer :
    def __init__(self, *writers) :
        self.writers = writers

    def write(self, text) :
        for w in self.writers :
            w.write(text)

import sys

saved = sys.stdout
fout = file('out.log', 'w')
sys.stdout = writer(sys.stdout, fout)
print "There you go."
sys.stdout = saved
fout.close()
Run Code Online (Sandbox Code Playgroud)

它对我来说就像一个魅力.它取自http://mail.python.org/pipermail/python-list/2003-February/188788.html

  • `saved = sys.stdout`是不必要的,`sys .__ stdout__`总是保存原来的`stdout`,所以最后只做`sys.stdout = sys .__ stdout__`. (3认同)

Kva*_*ant 10

class MovieDesc:
    name = "Name"
    genders = "Genders"
    country = "Country"

 def __str__(self):
#Do whatever you want here
        return "Name: {0}\tGenders: {1} Country: {2} ".format(self.name,self.genders,self.country)

)
Run Code Online (Sandbox Code Playgroud)

  • 我想知道这是什么。这与问题无关。 (3认同)

小智 6

举一个非常简单的例子,从 Python3.4 开始(尚未使用旧版本进行测试),这对我来说效果很好(放置在模块顶部):

import time
def dprint(string):
  __builtins__.print("%f -- %s" % (time.time(), string))

print = dprint
Run Code Online (Sandbox Code Playgroud)

注意,这仅在字符串参数是字符串时才有效... YMMV


Joo*_*kka 3

在 Python 2.x 中你不能,因为 print 不是一个函数,它是一个语句。在Python 3中, print 是一个函数,所以我想它可以被重写(不过还没有尝试过)。