[英]Python can't consistently find a module while the parent directory is in sys.path
I'm currently working on a project where I need to import self made modules that could be anywhere on the filesystem.我目前正在做一个项目,我需要导入可能位于文件系统任何位置的自制模块。 But python can't seem to consistently import them.但是 python 似乎无法始终如一地导入它们。
All the modules have the same name which is why I couple them with their parent directory, like so: xyz.abc
for a module called abc.py
in a folder called xyz
.所有模块都具有相同的名称,这就是为什么我将它们与它们的父目录结合起来,如下所示: xyz.abc
用于名为xyz
的文件夹中名为abc.py
的模块。 xyz's parent directory is added to path. xyz 的父目录被添加到路径中。 To import them later on, I use importlib.import_module(module_name)
where module name is xyz.abc
.为了稍后导入它们,我使用importlib.import_module(module_name)
其中模块名称为xyz.abc
。
To test my code, I am using python's tempfile lib to create temporary directories and temporary files.为了测试我的代码,我使用 python 的 tempfile 库来创建临时目录和临时文件。 ( /tmp
on my system is cleaned at reboot and not automatically.) (我系统上的/tmp
在重新启动时被清理,而不是自动清理。)
I've tried adding an __init__.py
file, it doesn't change anything.我试过添加一个__init__.py
文件,它不会改变任何东西。 I've also tried os.sync()
to force write the file to my disk thinking it might be a race problem but it didn't help.我也尝试过os.sync()
强制将文件写入我的磁盘,认为这可能是一个竞争问题,但它没有帮助。
Here's the code where it breaks:这是它中断的代码:
if parent not in sys.path:
sys.path.insert(0, parent)
module_name = os.path.basename(dir_path) + "." + filename.split(".")[0]
return importlib.import_module(module_name)
The tree structure of the directory is:目录的树结构为:
/tmp/tmp9tp_1j_q/
└── tmprvbxhk3t.py
And sys.path
has '/tmp'
in it when I print it right before module_name =...
.当我在module_name =...
之前打印sys.path
时,其中包含'/tmp'
。
When executing the code, sometimes it works and sometimes it doesn't .执行代码时,有时有效,有时无效。 I get: ModuleNotFoundError: No module named 'tmpfjig62pf'
我得到: ModuleNotFoundError: No module named 'tmpfjig62pf'
I'm thinking maybe sys.path
isn't internally updated directly after an insert.我在想也许sys.path
在插入后没有直接在内部更新。
I need some help to solve this problem.我需要一些帮助来解决这个问题。
The problem isn't in sys.path
, but it's close.问题不在sys.path
中,但很接近。 It is the Finder object in sys.meta_path
that uses sys.path
and sys.path_hooks
to look for modules, and sys.meta_path
has internal caches that aren't "refreshed" automatically in such a situation. sys.meta_path 中的 Finder sys.meta_path
使用sys.path
和sys.path_hooks
来查找模块,并且sys.meta_path
具有在这种情况下不会自动“刷新”的内部缓存。
So, to successfully import a module that's been created after the interpreter began execution, the internal caches of sys.meta_path
should be invalidated.因此,要成功导入解释器开始执行后创建的模块, sys.meta_path
的内部缓存应该无效。
That can be achieved by calling importlib.invalidate_caches()
after creating the test modules.这可以通过在创建测试模块后调用importlib.invalidate_caches()
来实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.