[英]import in python when two folders with same name
I have what it seems to be an unusual situation. 我有一种异常情况。
── folder1
├── run.py
└── pgm.py
── folder2
└── src
├── fileA.py
└── fileB.py
── folder3
└── src
├── file1.py
└── file2.py
Folder1 is mine, folders 2 and 3 are in forked and I don't want to change it, and I'm not sure I can put the three of them in a over-Folder. Folder1是我的文件夹,文件夹2和3是分叉的,我不想更改它,而且我不确定是否可以将其中三个文件夹放在文件夹中。
In run.py, I have: 在run.py中,我有:
sys.path.append(path_folder2)
from src.fileA import classA
That ClassA, call pgm.py thanks to: 该ClassA,由于以下原因调用pgm.py:
module = importlib.import_module('pgm')
And pgm tries to import file1.py in folder3.src which import himself only files of folder3. 然后pgm尝试将folder3.src中的file1.py导入,仅将自己的folder3文件导入。 Adding folder3 to path raise an ImportError.
将folder3添加到路径会引发ImportError。 I presume it's because python looks in the subfolder src of folder2, how can I force to look in folder3 ?
我认为这是因为python在folder2的子文件夹src中查找,如何强制在folder3中查找?
In fact I'd like to be in the folder2 environnment as if folder 3 doesn't exist and then in folder3 as if folder2 doesn't exist during the same execution. 实际上,我想进入Folder2环境,就好像文件夹3不存在,然后又想进入Folder3,就好像文件夹2在同一执行过程中不存在一样。 How can I do that ?
我怎样才能做到这一点 ?
Note: I didn't wrote the init.py for readability but they are in my folders and subfolders I tried to play with path, removing folder2 just before importing file1.py but no success. 注意:我没有写init.py来提高可读性,但是它们位于我尝试使用path播放的文件夹和子文件夹中,只是在导入file1.py之前删除了folder2,但没有成功。
You can rename module on import, like this: 您可以在导入时重命名模块,如下所示:
from src.fileA import classA as fileAclassA
from src.fileB import classA as fileBclassA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.