从模块导入与Python中的可执行文件同名的模块 [英] Importing from module with the same name as executable file in Python
问题描述
我有一个可执行文件,例如,resource.py
.它放置在名为resource
的文件夹中.重命名文件或文件夹是令人讨厌的-它是旧产品,并且用户习惯于使用此类命名.在旧版本中,它在另一个项目下,因此导入它的音像是import main_product.resource.<..>
.
I have an executable file, named, for example, resource.py
. It is disposed in the folder named resource
. Renaming file or folder is objectionable - it is old product and users accustomed to use such naming. At old version it was under another project, so imports to it sound like import main_product.resource.<..>
.
现在我需要使用import resource.<..>
和__import__('resource.<..>', ...)
之类的导入.然后尝试一下,出现预期的错误,因为Python首先尝试从文件resource.py
导入.
Now I need to use imports like import resource.<..>
and __import__('resource.<..>', ...)
. Then I try it, I get an expected error, because Python try to import from the file resource.py
first.
建议解决方案:
- 从
sys.path
删除当前文件夹的路径:- 在文件的开头,我们需要一小段代码;
- 此文件夹中没有相对导入;
- remove path of current folder from
sys.path
:- we need an ugly chunk of code at the begin of the file;
- no relative imports will be available in this folder;
- 文件开头的较大的丑陋代码段;
- 我不确定此功能是否会一直完美运行.
对此有任何有用的想法吗?
Have any usable idea about this?
P.S. Python v2.6,FreeBSD 7.3
P.S. Python v2.6, FreeBSD 7.3
推荐答案
使用imp.find_module()
和imp.load_module()
find_module
可让您指定自己的搜索路径
find_module
lets you specify your own path to search
这篇关于从模块导入与Python中的可执行文件同名的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!