简体   繁体   中英

How to import multiple files with same name in python

I have following structure for a python project that generate source files:

/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:

/project_name/prj/generate_all.py

How may I import generate scripts from generate_all ? 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. I don't want to add __init__.py file in module_nameK folders as I have only other source files there.

Take a look at the imp module.

EDIT

I think you need imp.load_source("somemodule.name", "full/path/to/your/module")


Your can use imp.load_module(name, ...)

An example taken from 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

import MySQLdb as mysql

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM