[英]Keeping Python packages with the same top-level name in different directories
I have several Python packages that I'd like to keep on separate filesystems but which unfortunately share the same top-level module name.我有几个 Python 包,我想将它们保留在单独的文件系统上,但不幸的是它们共享相同的顶级模块名称。
To illustrate, the directory structure looks like this:为了说明,目录结构如下所示:
/fs1
/top
__init__.py
/sub1
__init__.py
/fs2
/top
__init__.py
/sub2
__init__.py
In Python 2.7, is there any way I can set up my PYTHONPATH
so that I could import both top.sub1
and top.sub2
into the same script?在 Python 2.7 中,有什么方法可以设置我的PYTHONPATH
以便我可以将top.sub1
和top.sub2
导入到同一个脚本中? Adding both /fs1
and /fs2
doesn't work, since it only allows one of the two submodules to be imported (whichever comes first on PYTHONPATH
).同时添加/fs1
和/fs2
不起作用,因为它只允许导入两个子模块之一(以PYTHONPATH
上的先到者为准)。
I could copy/symlink the two trees into one, but for practical reasons I'd rather not do that.我可以将两棵树复制/符号链接为一棵树,但出于实际原因,我宁愿不这样做。
There are several options, one of which is imp
:有几种选择,其中之一是imp
:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
Another is with importlib
另一个是使用importlib
Relative:亲属:
importlib.import_module('.sub1', 'fs1.top')
Absolute:绝对:
importlib.import_module('fs1.top.sub1')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.