gpt4 book ai didi

python - 如何在 Python 3 中覆盖 file.write()?

转载 作者:太空宇宙 更新时间:2023-11-04 01:42:59 24 4
gpt4 key购买 nike

下面的代码适用于 Python 2.6 但不适用于 Python 3.x:

old_file_write = file.write 

class file():
def write(self, d):
if isinstance(d, types.bytes):
self.buffer.write(d)
else:
old_file_write(d)

# ... some code I cannot change or do not want to change
f = open("x")
f.write("...")
f.write(b"...")
sys.stdout.write(b"...")
sys.stdout.write("...")
print(b"...")
print("...")

问题是在 Python 3.x 中第一行会产生一个错误:

NameError: name 'file' is not defined

如何在 Python 3.x 中完成这项工作?

事实上,两年后,我仍在寻找适用于两个版本(2.5+ 和 3.x)的解决方案。

对于那些仍然想知道我为什么要找这个的人来说,这只是为了能够使旧代码(其他代码,有时您无法修改)与更新版本的 python 一起工作。

这不是关于我的代码,而是关于如何编写一些能够很好地处理糟糕代码的代码:)

最佳答案

我看到两个问题。

1:您的file 类未继承自任何特定类。如果我对情况的解释正确,它应该是 io.TextIOWrapper 的子类。

2:在 Python 2.6 和 3.x 中,types 模块(首先需要导入)没有元素 bytes。推荐的方法是单独使用 bytes

重做片段:

import io, sys

class file(io.TextIOWrapper):
def write(self, d, encoding=sys.getdefaultencoding()):
if isinstance(d, bytes):
d = d.decode(encoding)
super().write(d)

old_stdout = sys.stdout # In case you want to switch back to it again

sys.stdout = file(open(output_file_path, 'w').detach()) # You could also use 'a', 'a+', 'w+', 'r+', etc.

现在它应该做你想做的事,使用 sys.stdout.write 到你指定的输出文件。 (如果您不想写入磁盘上的文件,而是希望写入默认的 sys.stdout 缓冲区,请使用 sys.stdout = file(sys.stdout.detach( )) 可能会起作用。)

请注意,由于 Python 3.x 没有 file 类,但 2.6 有 io 模块,您将不得不使用其中一个类io 模块。我上面的代码只是一个例子,如果你想让它更灵活,你必须自己解决。也就是说,根据您要写入的文件类型/写入模式,您可能希望在 io 中使用不同的类。

关于python - 如何在 Python 3 中覆盖 file.write()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3046066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com