[英]How to import a user module which has the same name with a system module?
I have a legacy python program which defined a module whose name conflict with a system module in the current python, what's the easiest method to fix this? 我有一个旧版python程序,该程序定义了一个模块,该模块的名称与当前python中的系统模块冲突,最简单的方法是解决此问题? This module has been imported in many place, so it would be great if no need to change the the old python source.
该模块已在很多地方导入,因此,如果不需要更改旧的python源代码,那就太好了。
You could create a custom import routine using the imp module
. 您可以使用
imp module
创建自定义导入例程。 For example, here I'm importing a module named string
which shadows the real string module: 例如,在这里我要导入一个名为
string
的模块,该模块会遮盖真实的字符串模块:
import imp
def user_import(name, path):
mod_file, mod_path, mod_desc = imp.find_module(name, [path])
return imp.load_module(name, mod_file, mod_path, mod_desc)
# load the real 'string' module
import string
print string.digits
# load the user 'string' module which lives under the path './foo'
mod = user_import('string', './foo')
print mod.digits
Output: 输出:
0123456789
thesearenotdigits
You can always rename a module when you import it, such as: 导入模块时,您始终可以重命名模块,例如:
import sys as realsys
将sys导入为realsys
realsys.exit(1)
realsys.exit(1)
It seems like you'll have to do this either for the system module whose name you have overloaded or for your module, depending on which causes the least pain. 似乎您必须对名称已重载的系统模块或模块进行此操作,具体取决于哪个模块导致的痛苦最少。
Bottom line, when you create modules, it's good to more fully qualify the name, eg instead of creating sys
(in this example), you could have created mylib.sys
. 最重要的是,创建模块时,最好完全限定名称,例如,可以创建
mylib.sys
而不是创建sys
(在此示例中)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.