Python 2自定义导入程序 - 导入模块vs导入包

时间:2015-10-14 10:29:25

标签: python-2.7 packages python-import python-module

在(遗留)代码中,我使用了自定义导入程序:

class UnicodeImporter(object):

    def find_module(self,fullname,path=None):
        if isinstance(fullname,unicode):
            fullname = fullname.replace(u'.',u'\\')
            exts = (u'.pyc',u'.pyo',u'.py')
        else:
            fullname = fullname.replace('.','\\')
            exts = ('.pyc','.pyo','.py')
        if os.path.exists(fullname) and os.path.isdir(fullname):
            return self
        for ext in exts:
            if os.path.exists(fullname+ext):
                return self

    def load_module(self,fullname):
        if fullname in sys.modules:
            return sys.modules[fullname]
        else: # set to avoid reimporting recursively
            sys.modules[fullname] = imp.new_module(fullname)
        if isinstance(fullname,unicode):
            filename = fullname.replace(u'.',u'\\')
            ext, initfile = u'.py', u'__init__'
        else:
            filename = fullname.replace('.','\\')
            ext, initfile = '.py', '__init__'
        try:
            if os.path.exists(filename+ext): # some foo.py
                with open(filename+ext,'U') as fp:
                    mod = imp.load_source(fullname,filename+ext,fp)
                    sys.modules[fullname] = mod
                    mod.__loader__ = self
            else: # some directory
                mod = sys.modules[fullname]
                mod.__loader__ = self
                mod.__file__ = os.path.join(os.getcwd(),filename)
                mod.__path__ = [filename]
                #init file
                initfile = os.path.join(filename,initfile+ext)
                if os.path.exists(initfile):
                    with open(initfile,'U') as fp:
                        code = fp.read()
                    exec compile(code, initfile, 'exec') in mod.__dict__
            return mod
        except Exception as e: # wrap in ImportError a la python2 - will keep
            # the original traceback even if import errors nest
            print 'fail', filename+ext
            raise ImportError, u'caused by ' + repr(e), sys.exc_info()[2]

if not hasattr(sys,'frozen'):
    sys.meta_path = [UnicodeImporter()]

代码为https://www.youtube.com/watch?v=rSAiSTkVMfs

我有两个问题:

  • 为什么人们使用不同的方式导入包和模块?我不能以某种方式在包路径中使用imp.load_source()吗? imp.load_module()?在这些情况下,mod.__loader__ = self的位置是否重要?基本上我正在寻找“正确的方法”
  • 是否应该使用imp.acquirelock()
  • 进行保护

0 个答案:

没有答案