我正在处理一个自定义文件路径类,它应该始终在写入相应的系统文件并关闭其文件对象后执行一个函数。该函数将文件路径的内容上传到远程位置。我希望从用户的角度来看,上传功能完全在幕后发生,即用户可以像使用任何其他os.PathLike
类一样使用该类并自动获取上传功能。下面的伪代码供参考。
import os
class CustomPath(os.PathLike):
def __init__(self, remote_path: str):
self._local_path = "/some/local/path"
self._remote_path = remote_path
def __fspath__(self) -> str:
return self._local_path
def upload(self):
# Upload local path to remote path.
Run Code Online (Sandbox Code Playgroud)
当用户直接调用任何方法时,我当然可以自动调用上传函数。
但是,我不清楚如果有人使用内置文件写入文件,如何自动调用上传功能open,如下所示。
custom_path = CustomPath("some remote location")
with open(custom_path, "w") as handle:
handle.write("Here is some text.")
Run Code Online (Sandbox Code Playgroud)
或者
custom_path = CustomPath("some remote location")
handle = open(custom_path, "w")
handle.write("Here is some text.")
handle.close()
Run Code Online (Sandbox Code Playgroud)
我希望与open函数调用兼容,以便上传行为适用于所有第三方文件编写器。这种行为在 Python 中是可能的吗?
根据您对 Girish Dattatray Hegde 的评论,您似乎想要执行以下操作来覆盖默认的 __exit__ 处理程序open:
import io
old_exit = io.FileIO.__exit__ # builtin __exit__ method
def upload(self):
print(self.read()) # just print out contents
def new_exit(self):
try:
upload(self)
finally:
old_exit(self) # invoke the builtin __exit__ method
io.FileIO.__exit__ = new_exit # establish our __exit__ method
with open('test.html') as f:
print(f.closed) # False
print(f.closed) # True
Run Code Online (Sandbox Code Playgroud)
不幸的是,上面的代码会导致以下错误:
test.py", line 18, in <module>
io.FileIO.__exit__ = new_exit # establish our __exit__ method
TypeError: can't set attributes of built-in/extension type '_io.FileIO'
Run Code Online (Sandbox Code Playgroud)
所以,我不相信你可以做你想做的事。最终,您可以创建自己的子类并重写方法,但不能替换现有内置open类的方法。