pythons 'print' 语句不调用 .write() 方法?

标签 python oop file inheritance printing

我认为 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 没有调用 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

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

我认为 print 只是调用了 write 方法 - 显然我遗漏了一些基本的东西。

最佳答案

显然,这是 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 但这没有任何区别。

关于pythons 'print' 语句不调用 .write() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7017778/

相关文章:

python - 如何使用python从页面下载文件

python - 有什么方法可以从python的pdf文件中提取没有任何网格的表?

c - 在 C 中一次读取 16 个字节的文件

java - 在java中将文件写入亚马逊s3

c - 字符串数组与用户字符串比较给出访问错误

python - 将 sqlite3.cursor 转换为 int PYTHON

python - 根据国家重新排列车牌字符

oop - 柯里化(Currying)和重载一样吗?

c++ - extern "C"的功能是什么?

oop - 为什么 Rust 不支持 trait 对象向上转换?