在导入的模块中模拟 python 的原生 `open` 函数
我想覆盖 python 的本机 open
函数。 这是我尝试过的。我的目录中有以下文件:
main.py
mock.py
test.txt
test_main.py
main.py
包含以下内容:
fs = open('test.txt', 'r')
mock.py
包含以下内容:
def open():
print("hello")
test.txt
包含以下内容:
abc
test_main.py
包含以下内容:
import pathlib
import mock
if __name__=="__main__":
file_path = pathlib.Path('test.txt')
open = mock.open
import main
file_path.unlink()
在 test_main.py
的第 6 行中,我尝试通过设置自己的内容来覆盖 将 mock.py
中的函数设置为关键字 open
。在 test_main.py
中 看起来 python 将使用我的定义。然而,在 导入的 main.py
看起来 python 仍然求助于本机定义,因此 python test_main.py
抛出以下错误:
PermissionError: [WinError 32] 该进程无法访问该文件,因为该文件正在被另一个进程使用:“test.txt”
如何重新定义 open
以便我的定义适用于所有 导入的命名空间?
I would like to overwrite python's native open
function.
Here's what I have tried. I have the following files in a directory:
main.py
mock.py
test.txt
test_main.py
main.py
contains the following:
fs = open('test.txt', 'r')
mock.py
contains the following:
def open():
print("hello")
test.txt
contains the following:
abc
test_main.py
contains the following:
import pathlib
import mock
if __name__=="__main__":
file_path = pathlib.Path('test.txt')
open = mock.open
import main
file_path.unlink()
In line 6 of test_main.py
I tried to overwrite by setting my own
function in mock.py
to the keyword open
. Within test_main.py
it looks like python will use my definition. However, within the
imported main.py
it looks like python still resorts to the native definition, such that python test_main.py
throws the following error:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'test.txt'
How can I redefine open
such that my definition applies to all
imported namespaces?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我刚刚找到它,感谢 这个问题。需要导入
builtins
:I just found it thanks to this question. Need to import
builtins
: