【问题标题】:pythons 'print' statement doesn't call the .write() method?python 'print' 语句不调用 .write() 方法?
【发布时间】:2011-08-10 21:03:30
【问题描述】:

我认为print 语句只是在sys.stdout(默认情况下)对象上调用了 .write() 方法。

但是写了一个这样的子类:

import time

class logfile(file):
    def __init__(self, *args, **kwargs):
        file.__init__(self, *args, **kwargs)

    def write(self, logstr):
        if logstr[-1] != '\n': logstr += '\n'
        super(logfile, self).write(time.strftime('%D-%T ') + str(logstr))

如果我创建一个logfile 对象并调用write 方法似乎可以工作,但是当尝试将sys.stdout 对象更改为logfile 的一个实例时,它看起来好像print 不是' t 打电话给write。也许writelines?

使用这个:

#!/usr/bin/python

from myfile import logfile
import sys

sys.stdout = logfile('somefile', 'w')

print 'this is a test'
sys.stdout.write('this is another test')

我的输出文件“somefile”包含:

this is a test
08/10/11-16:59:47 this is another test

你可以看到输出文件的第一行是我尝试print的内容,第二行是sys.stdout.write中使用的内容

我以为 print 只是调用了 write 方法——显然我缺少一些基本的东西。

【问题讨论】:

  • print 有自己对 stdout 的引用。
  • @Evpok 我认为如果他尝试重定向打印而不是使用普通日志记录,他可能不想修改预先存在的 print 语句。
  • 您应该使用日志记录模块来记录文件。更可配置。
  • 您是故意避免使用 Python 的日志记录模块,还是这只是替代实现中的练习?

标签: python oop file inheritance printing


【解决方案1】:

显然这是 Python 2 实现的一个限制,其中 print 是一个语句,而不是具有副作用的表达式(就像在 Python 3 中一样)。

我将代码重写为可在 Python 3 中使用的代码:

from io import FileIO
import time

class logfile(FileIO):
  def __init__(self, *args, **kwargs):
    FileIO.__init__(self, *args, **kwargs)

  def write(self, logstr):
    if logstr[-1] == '\n': logstr = logstr[:-1]
    super(logfile, self).write(bytes(time.strftime('%D-%T ') + str(logstr), 'UTF-8'))

import sys

sys.stdout = logfile('somefile', 'w')

print("This is a test")
sys.stdout.write('this is another test')

据我所知,没有办法在 Python 2 中创建相同的行为。

我也尝试过使用from __future__ import print_function,但这并没有什么不同。

【讨论】:

    【解决方案2】:

    如果将文件放在实例变量中,它似乎可以工作。

    import time
    
    class logfile(object):
        def __init__(self, *args, **kwargs):
            self.f = file(*args, **kwargs)
        def write(self, logstr):
            if logstr[-1] != '\n': logstr += '\n'
            self.f.write(time.strftime('%D-%T ') + str(logstr))
    

    不幸的是,它记录了额外的空行,这是一种解决方案(print '2', '3', '4' 写入 3 个条目):

    class logfile(object):
        def __init__(self, *args, **kwargs):
            self.f = file(*args, **kwargs)
            self.c = False
        def write(self, logstr):
            self.c = not self.c
            if logstr[-1] != '\n': logstr += '\n'
            if self.c:
                self.f.write(time.strftime('%D-%T ') + str(logstr))
    

    这个记录完整行(注意:print "4\n", "5" 仍然是 2 个记录行):

    class logfile(object):
        def __init__(self, *args, **kwargs):
            self.f = file(*args, **kwargs)
            self.newline = True
        def write(self, logstr):
            if self.newline:
                self.f.write(time.strftime('%D-%T '))
            self.f.write(logstr)
            self.newline = logstr[-1] == '\n'
    

    有人知道如何在 1 条日志中处理完整的打印语句吗?

    【讨论】:

      【解决方案3】:

      This article 解释了您的问题。基本上如果sys.stdout 是file 的子类,那么print 绕过sys.stdout.write 并直接写入sys.stdout.fd。

      您的问题的解决方案是使用组合而不是子类化file。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-29
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多