重载打印python

我能够超载的printfunction,并从内部调用正常的function? 我想要做的是在我想要print的特定行后打电话给我的print ,这将print正常的print和复制到文件。

另外我不知道如何超载print 。 我不知道如何做可变长度的参数。 我会尽快查找它,但重载打印python只是告诉我,我不能超载在2.x这是我正在使用的print

对于那些回顾以前的date的答案,截至版本发布“Python 2.6”,原始海报的问题有一个新的答案。

在Python 2.6及更高版本中,您可以禁用打印语句而转而使用打印function,然后使用自己的打印function覆盖打印function:

 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) 

当然你需要考虑这个打印function在这个时候只是模块范围。 你可以select覆盖__builtin__.print ,但是你需要保存原来的__builtin__.print ; 可能会使用__builtin__命名空间。

重载print是python 3.0的一个devise特性来解决你在python 2.x中不能这样做的能力。

但是,您可以覆盖sys.stdout。 ( 例子 )只要将它分配给另一个文件类的对象,它就是你想要的。

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

我遇到了同样的问题。

这个怎么样:

 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() 

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

 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) ) 

尽pipe不能replaceprint关键字(在Python 2.x中, print是一个关键字),但是通常会replacesys.stdout来执行类似于print重载的操作。 例如,用一个StringIO.StringIO的实例。 这将捕获StringIO实例中的所有打印数据,之后您可以操作它。

在Python 2.x中你不能,因为print不是一个函数,而是一个声明。 在Python 3中打印是一个函数,所以我想它可以被覆盖(虽然没有尝试过)。

我在另一个SO问题上回答了同样的问题

从本质上讲,最简单的解决scheme是在wsgiconfiguration文件中将输出redirect到stderr,如下所示。

 sys.stdout = sys.stderr 

只是想我会添加我的想法…适合我的目的是能够在Eclipse中运行sthg,然后从(Windows)CLI运行,而不用每个打印语句都得到编码exception。 无论你做什么,都不要使EncodingStdout成为类文件的一个子类:“self.encoding = encoding”这行就会导致编码属性为None!

注意一件事,我在一天中发现与这东西拼图是编码exception得到之前,得到“打印”或“写”:这是当参数化string(即“mondodod%s等等等等%s”% “blip”,“blap”))由…构成…什么? “框架”?

 class EncodingStdout( object ): def __init__( self, encoding='utf-8' ): self.encoding = encoding def write_ln( self, *args ): if len( args ) < 2: sys.__stdout__.write( args[ 0 ] + '\n' ) else: if not isinstance( args[ 0 ], basestring ): raise Exception( "first arg was %s, type %s" % ( args[ 0 ], type( args[ 0 ]) )) # if the default encoding is UTF-8 don't bother with encoding if sys.getdefaultencoding() != 'utf-8': encoded_args = [ args[ 0 ] ] for i in range( 1, len( args )): # numbers (for example) do not have an attribute "encode" if hasattr( args[ i ], 'encode' ): encoded_args.append( args[ i ].encode( self.encoding, 'replace' ) ) else: encoded_args.append( args[ i ]) args = encoded_args sys.__stdout__.write( args[ 0 ] % tuple( args[ 1 : ] ) + '\n' ) # write seems to need a flush sys.__stdout__.flush() def __getattr__( self, name ): return sys.__stdout__.__getattribute__( name ) print "=== A mondodod %s %s" % ( "été", "pluviôse, irritée contre la ville entière" ) sys.stdout = EncodingStdout() sys.stdout.write_ln( "=== B mondodod %s %s", "été", "pluviôse, irritée contre la ville entière" ) # convenience method def pr( *args ): sys.stdout.write_ln( *args ) pr( "=== C mondodod %s %s", "été", "pluviôse, irritée contre la ville entière" ) 

对于一个非常简单的例子,从Python3.4开始(还没有用老版本testing过),这对我很好(放在模块的顶部):

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

请注意,这只适用于如果string参数是一个str … YMMV