[英]How to import multiple files with same name in python
I have following structure for a python project that generate source files: 对于生成源文件的python项目,我具有以下结构:
/project_name/src/module_name0/scripts/generate.py
/project_name/src/module_name1/scripts/generate.py
...
/project_name/src/module_nameN/scripts/generate.py
I want use generate
scripts from script located in: 我想使用位于以下位置的脚本
generate
脚本:
/project_name/prj/generate_all.py
How may I import generate
scripts from generate_all
? 如何从
generate_all
导入generate
脚本? I tried to add /project_name/src/module_nameK
to sys.path
, but because the files have same name one of them hides the others. 我试图将
/project_name/src/module_nameK
添加到sys.path
,但是由于文件具有相同的名称,其中一个隐藏了其他文件。 I don't want to add __init__.py
file in module_nameK
folders as I have only other source files there. 我不想在
module_nameK
文件夹中添加__init__.py
文件,因为那里只有其他源文件。
Take a look at the imp module. 看一下imp模块。
I think you need imp.load_source("somemodule.name", "full/path/to/your/module")
我认为您需要
imp.load_source("somemodule.name", "full/path/to/your/module")
Your can use imp.load_module(name, ...)
您可以使用
imp.load_module(name, ...)
An example taken from python docs: 取自python docs的示例:
import imp
import sys
def __import__(name, globals=None, locals=None, fromlist=None):
# Fast path: see if the module has already been imported.
try:
return sys.modules[name]
except KeyError:
pass
# If any of the following calls raises an exception,
# there's a problem we can't handle -- let the caller handle it.
fp, pathname, description = imp.find_module(name)
try:
return imp.load_module(name, fp, pathname, description)
finally:
# Since we may exit via an exception, close fp explicitly.
if fp:
fp.close()
You can always try: 您可以随时尝试:
import xxx as yyy
So for example if you want to rename MySQLdb to something easier to type, you could write 因此,例如,如果您想将MySQLdb重命名为更易于键入的名称,则可以编写
import MySQLdb as mysql
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.