导入同名的Python模块

10 投票
1 回答
8756 浏览
提问于 2025-04-16 21:08

我有几个Python项目,它们都有一个叫做conf的包:

/some_folder/project_1/
  conf/
    __init__.py
    some_source_file.py

/another_folder/project_2/
  conf/
    __init__.py
    another_source_file.py

对于每个项目,我在site-packages文件夹里创建了一个.pth文件,里面的内容是:

.../site-packages/project_1.pth:
import sys; sys.path.append('/some_folder/project_1/')

.../site-packages/project_2.pth:
import sys; sys.path.append('/another_folder/project_2/')

我可以访问/some_folder/project_1/里的模块:

import conf.some_source_file

但是无法访问/another_folder/project_2/里的模块:

import conf.another_source_file
AttributeError: 'module' object has no attribute 'another_source_file'

看起来Python只会在sys.path中的文件夹下搜索第一个conf路径。有没有办法解决这个问题?

1 个回答

9

不可以。你需要给其中一个改个名字,或者把项目文件夹变成一个包,然后通过那个包来导入。

撰写回答