Python重写print()

2024-10-04 11:35:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是mod_wsgi,我想知道是否可以重写print()命令(因为它毫无用处)。在

这样做行不通:

print = myPrintFunction

因为这是个语法错误。:(


Tags: 命令modwsgiprint语法错误myprintfunction
3条回答

Print在python2.x中不是一个函数,因此这是不可能直接实现的。在

但是,您可以override sys.stdout。在

如果您使用的是python3.0,其中print is now a function那么,假设您有正确的签名,那么您所拥有的就可以工作了。另请参阅本网站中的a related question。在

如果您使用的是3.0,则print是一个函数。如果您使用的是2.6,您可以from __future__ import print_function并继续使用打印函数。在

如果<;=2.5,您可以像其他人建议的那样替换stdout,但是如果您的wsgi服务器同时在多个线程中调用您的应用程序,请非常小心。您的在同一管道中同时发送请求。在

我还没有测试过,但你可以试试这样的方法:

import sys
import threading

class ThreadedStdout(object):
    def __init__(self):
        self.local = threading.local()
    def register(self, fh):
        self.local.fh = fh
    def write(self, stuff):
        self.local.fh.write(stuff)

sys.stdout = ThreadedStdout()

def app(environ, start):
    sys.stdout.register(environ['wsgi.stdout'])

    # Whatever.

import sys
sys.stdout = MyFileWrapper()

或者类似的工作?在

相关问题 更多 >