从模块导入与Python中的可执行文件同名的模块 [英] Importing from module with the same name as executable file in Python

查看:100
本文介绍了从模块导入与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.

建议解决方案:

  1. sys.path删除当前文件夹的路径:
    • 在文件的开头,我们需要一小段代码;
    • 此文件夹中没有相对导入;
  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆