gpt4 book ai didi

python - 覆盖 __import__ 后是否可以恢复?

转载 作者:行者123 更新时间:2023-12-01 04:50:26 25 4
gpt4 key购买 nike

我正在尝试编写一些能够抵抗 __import__ 被更改的代码,因为 the Pydev debugger overrides __import__ .

所以,我需要一种访问内置 __import__ 函数的方法。

>>> def fake_import(*args, **kwargs): pass # some other implementation here
...
>>> import __builtin__
>>> __builtin__.__import__ = fake_import
# can I recover the original value of __import__ here?

SO 上有关于 recovering removed built-ins 的问题但在这种情况下,全局已被替换。

最佳答案

这是一个有点棘手的问题,因为 python 不会对重新加载 __builtin__ 感兴趣。模块,因为它没有改变。您将被迫删除 __builtin__ module 以便强制 python 重新导入它。您也可以绕过__import__通过使用importlib (仅在 python3 中如此,在 python2 中 importlib 求助于 __import__ )。

import sys
import importlib

import __builtin__ as old_builtins

class ExampleImporter(object):
old_import = __import__
def __init__(self):
self.count = 0
def new_import(self, *args, **kwargs):
self.count += 1
print(args, kwargs)
return self.old_import(*args, **kwargs)
importer = ExampleImporter()

old_builtins.__import__ = importer.new_import
assert __import__ == importer.new_import

# remove builtins from modules so as to force its reimport
del sys.modules["__builtin__"]
# in python3 the following bypasses __import__ entirely, but not in python2
new_builtins = importlib.import_module("__builtin__")
# restore initial state of __builtin__ module (will not delete new names
# added to __builtin__)
old_builtins.__dict__.update(new_builtins.__dict__)
# Replace new __builtin__ with old __builtin__ module. Otherwise you'll end up with a
# mess where different modules have different a __builtin__ module.
sys.modules["__builtin__"] = old_builtins
del new_builtins

assert __import__ == importer.old_import
assert importer.count == 1 # would be 0 in python3

关于python - 覆盖 __import__ 后是否可以恢复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28607701/

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