在导入的模块中模拟 python 的原生 `open` 函数

发布于 2025-01-13 16:53:14 字数 1000 浏览 3 评论 0原文

我想覆盖 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

○闲身 2025-01-20 16:53:14

我刚刚找到它,感谢 这个问题。需要导入builtins

import pathlib
import mock
import builtins

if __name__=="__main__":
  file_path = pathlib.Path('test.txt')  
  builtins.open = mock.open
  import main
  file_path.unlink()

I just found it thanks to this question. Need to import builtins:

import pathlib
import mock
import builtins

if __name__=="__main__":
  file_path = pathlib.Path('test.txt')  
  builtins.open = mock.open
  import main
  file_path.unlink()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文