【问题标题】:import in python when two folders with same name当两个同名文件夹时在python中导入
【发布时间】:2013-12-20 18:56:48
【问题描述】:

我的情况似乎很不寻常。

── folder1
     ├── run.py
     └── pgm.py

── folder2
      └── src
           ├── fileA.py
           └── fileB.py

── folder3
      └── src
           ├── file1.py
           └── file2.py

文件夹 1 是我的,文件夹 2 和 3 是分叉的,我不想更改它,我不确定是否可以将它们三个放在一个重叠文件夹中。

在 run.py 中,我有:

    sys.path.append(path_folder2)
    from src.fileA import classA

那个 ClassA,调用 pgm.py 感谢:

     module = importlib.import_module('pgm')

而 pgm 尝试在 folder3.src 中导入 file1.py,它只导入自己的文件夹 3 的文件。将 folder3 添加到路径会引发 ImportError。我想这是因为 python 在 folder2 的子文件夹 src 中查找,我该如何强制在 folder3 中查找?

事实上,我想在 folder2 环境中,好像文件夹 3 不存在,然后在 folder3 中,好像在同一执行期间 folder2 不存在。我怎样才能做到这一点 ?

注意: 为了便于阅读,我没有编写 init.py,但它们在我的文件夹和子文件夹中 我尝试使用路径,在导入 file1.py 之前删除文件夹 2,但没有成功。

【问题讨论】:

  • 什么是“错误”?
  • 错误说明了什么??
  • 对不起:ImportError: No module named file1
  • 为什么不将src 目录添加到路径中? src 在我看来它们包含 python 模块,而不是 src 包。
  • 通过 sys.path.append ?如果我这样做了,fileA.py 不能再通过 import fileB 来导入 fileB.py。

标签: python import


【解决方案1】:

您可以在导入时重命名模块,如下所示:

from src.fileA import classA as fileAclassA
from src.fileB import classA as fileBclassA

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 2018-06-17
    相关资源
    最近更新 更多