- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试让以下行为发挥作用:
from my_module import some_random_string
我的模块应该拦截它并根据some_random_string
返回某些值。
我尝试设置导入 Hook ,但它没有按预期工作:
# custom_import.py
import sys
class MyImporter(object):
def find_module(self, filename, path):
print(filename, path)
return "foobar"
def load_module(self, module_name):
print(module_name)
return "foobar"
sys.meta_path.append(MyImporter())
# interactive console
>>> from custom_import import some_string
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name some_string
>>>
为什么会这样以及如何解决这个问题?
最佳答案
能够导入 my_module
中不存在的任何对象(假设my_module
存在并且可访问)我们可以从简单的包装my_module
开始喜欢
import importlib
import sys
import types
class ModuleWrapper:
def __init__(self, module):
self.module = module
@property
def __path__(self):
return None
def __getattr__(self, name):
try:
return getattr(self.module, name)
except AttributeError:
# returning `module` object is not necessary,
# can be something else
return types.ModuleType(name)
my_module = importlib.import_module('my_module')
sys.modules['my_module'] = ModuleWrapper(my_module)
具有项目结构
my_module.py
test.py
及内容
my_module.py:
...snippet above...
some_name = 'Sample text'
test.py:
from my_module import some_name, z
print(some_name)
print(z)
执行中
> python test.py
给我们提供Python2.7.0
Sample text
<module 'z' (built-in)>
以及Python3.5.4
Sample text
<module 'z'>
关于python - 覆盖 `from my_module import ...`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51087634/
在我的程序中,我有一个名为 core.Module 的接口(interface)和一个实现此接口(interface)的结构,名为 my_module.MyModule。创建这些实现我的接口(inte
我正在尝试让以下行为发挥作用: from my_module import some_random_string 我的模块应该拦截它并根据some_random_string返回某些值。 我尝试设置导
此示例脚本: #!/usr/bin/perl -w while (1) { sleep(1); } 大约需要 264 kB grep -A1 heap /proc/9216/smaps 0817
我已经编写了一个自定义模块,但安装时遇到问题。这是模块的结构。 ├── my_module │ ├── .git │ │ ├── │ ├── build │ │ ├── │
好的,我将代码剥离到极少以说明问题并使其可重现 语境 : Python 3.7 没有 VENV 或有趣的东西 说话便宜。给你看代码: 代码结构: $ tree pymod/ pymod/ ├── mo
我有一个模块 my_module,它由大量文件使用: 从 my_module 导入 * 在模块里面,能知道是哪个文件导入了这个模块吗? 我想知道进行此导入的文件名:line_no。 所以我需要的代码是
我想对我的类进行单元测试,它位于另一个名为 client_blogger.py 的文件中。 我的单元测试文件在同一目录中。我的所有其他单元测试都有效,除非我尝试模拟我自己的方法之一。 ## unit_
我有一个要运行的 Python 脚本。当我从 PyCharm 中运行它时它运行没有问题,但是当我通过终端运行它时使用: python my_script.py 我得到: Traceback (most
我在 my_module 中定义了一个类 MyClass。 MyClass 有一个方法 pickle_myself 可以 pickle 相关类的实例: def pickle_myself(self,
#include #include #include #include #include #include #include #include #include #include
我是一名优秀的程序员,十分优秀!