• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python zipimport.zipimporter函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中zipimport.zipimporter函数的典型用法代码示例。如果您正苦于以下问题:Python zipimporter函数的具体用法?Python zipimporter怎么用?Python zipimporter使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了zipimporter函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: testZipImporterMethods

    def testZipImporterMethods(self):
        packdir = TESTPACK + os.sep
        packdir2 = packdir + TESTPACK2 + os.sep
        files = {packdir + "__init__" + pyc_ext: (NOW, test_pyc),
                 packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
                 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc),
                 "spam" + pyc_ext: (NOW, test_pyc)}

        z = ZipFile(TEMP_ZIP, "w")
        try:
            for name, (mtime, data) in files.items():
                zinfo = ZipInfo(name, time.localtime(mtime))
                zinfo.compress_type = self.compression
                zinfo.comment = b"spam"
                z.writestr(zinfo, data)
            z.close()

            zi = zipimport.zipimporter(TEMP_ZIP)
            self.assertEqual(zi.archive, TEMP_ZIP)
            self.assertEqual(zi.is_package(TESTPACK), True)

            find_mod = zi.find_module('spam')
            self.assertIsNotNone(find_mod)
            self.assertIsInstance(find_mod, zipimport.zipimporter)
            self.assertFalse(find_mod.is_package('spam'))
            load_mod = find_mod.load_module('spam')
            self.assertEqual(find_mod.get_filename('spam'), load_mod.__file__)

            mod = zi.load_module(TESTPACK)
            self.assertEqual(zi.get_filename(TESTPACK), mod.__file__)

            existing_pack_path = importlib.import_module(TESTPACK).__path__[0]
            expected_path_path = os.path.join(TEMP_ZIP, TESTPACK)
            self.assertEqual(existing_pack_path, expected_path_path)

            self.assertEqual(zi.is_package(packdir + '__init__'), False)
            self.assertEqual(zi.is_package(packdir + TESTPACK2), True)
            self.assertEqual(zi.is_package(packdir2 + TESTMOD), False)

            mod_path = packdir2 + TESTMOD
            mod_name = module_path_to_dotted_name(mod_path)
            mod = importlib.import_module(mod_name)
            self.assertTrue(mod_name in sys.modules)
            self.assertEqual(zi.get_source(TESTPACK), None)
            self.assertEqual(zi.get_source(mod_path), None)
            self.assertEqual(zi.get_filename(mod_path), mod.__file__)
            # To pass in the module name instead of the path, we must use the
            # right importer
            loader = mod.__loader__
            self.assertEqual(loader.get_source(mod_name), None)
            self.assertEqual(loader.get_filename(mod_name), mod.__file__)

            # test prefix and archivepath members
            zi2 = zipimport.zipimporter(TEMP_ZIP + os.sep + TESTPACK)
            self.assertEqual(zi2.archive, TEMP_ZIP)
            self.assertEqual(zi2.prefix, TESTPACK + os.sep)
        finally:
            z.close()
            os.remove(TEMP_ZIP)
开发者ID:3lnc,项目名称:cpython,代码行数:59,代码来源:test_zipimport.py


示例2: test_cache

 def test_cache(self):
     self.writefile('x.py', 'y')
     from zipimport import _zip_directory_cache, zipimporter
     new_importer = zipimporter(self.zipfile)
     try:
         assert zipimporter(self.zipfile) is not new_importer
     finally:
         del _zip_directory_cache[self.zipfile]
开发者ID:Darriall,项目名称:pypy,代码行数:8,代码来源:test_zipimport.py


示例3: testUnencodable

 def testUnencodable(self):
     filename = support.TESTFN_UNENCODABLE + ".zip"
     self.addCleanup(support.unlink, filename)
     with ZipFile(filename, "w") as z:
         zinfo = ZipInfo(TESTMOD + ".py", time.localtime(NOW))
         zinfo.compress_type = self.compression
         z.writestr(zinfo, test_src)
     zipimport.zipimporter(filename).load_module(TESTMOD)
开发者ID:Eyepea,项目名称:cpython,代码行数:8,代码来源:test_zipimport.py


示例4: execfilename

def execfilename(filename):
    if filename.endswith('.py'):
        execfile(filename)
    elif filename.endswith('.zip'):
        sys.path.insert(0, filename)
        exec zipimport.zipimporter(filename).get_code('__main__')
    else:
        raise ValueError('filename=%r is not a valid python file' % filename)
开发者ID:vilic,项目名称:pybuild,代码行数:8,代码来源:test.py


示例5: _tool_module

    def _tool_module(self):
        # TODO: Interchange zipimport with normal initilization for better error reporting
        oldpythonpath = sys.path
        sys.path = self.toolpath + sys.path

        try:
            try:
                file, path, desc = imp.find_module(self.name, self.toolpath)
                try:
                    return imp.load_module(self.name, file, path, desc)
                finally:
                    if file:
                        file.close()
            except ImportError as e:
                if str(e)!="No module named %s"%self.name:
                    raise SCons.Errors.EnvironmentError(e)
                try:
                    import zipimport
                except ImportError:
                    pass
                else:
                    for aPath in self.toolpath:
                        try:
                            importer = zipimport.zipimporter(aPath)
                            return importer.load_module(self.name)
                        except ImportError as e:
                            pass
        finally:
            sys.path = oldpythonpath

        full_name = 'SCons.Tool.' + self.name
        try:
            return sys.modules[full_name]
        except KeyError:
            try:
                smpath = sys.modules['SCons.Tool'].__path__
                try:
                    file, path, desc = imp.find_module(self.name, smpath)
                    module = imp.load_module(full_name, file, path, desc)
                    setattr(SCons.Tool, self.name, module)
                    if file:
                        file.close()
                    return module
                except ImportError as e:
                    if str(e)!="No module named %s"%self.name:
                        raise SCons.Errors.EnvironmentError(e)
                    try:
                        import zipimport
                        importer = zipimport.zipimporter( sys.modules['SCons.Tool'].__path__[0] )
                        module = importer.load_module(full_name)
                        setattr(SCons.Tool, self.name, module)
                        return module
                    except ImportError as e:
                        m = "No tool named '%s': %s" % (self.name, e)
                        raise SCons.Errors.EnvironmentError(m)
            except ImportError as e:
                m = "No tool named '%s': %s" % (self.name, e)
                raise SCons.Errors.EnvironmentError(m)
开发者ID:blag,项目名称:keyczar,代码行数:58,代码来源:__init__.py


示例6: testUnencodable

 def testUnencodable(self):
     filename = support.TESTFN_UNENCODABLE + ".zip"
     z = ZipFile(filename, "w")
     zinfo = ZipInfo(TESTMOD + ".py", time.localtime(NOW))
     zinfo.compress_type = self.compression
     z.writestr(zinfo, test_src)
     z.close()
     try:
         zipimport.zipimporter(filename)
     finally:
         os.remove(filename)
开发者ID:alfonsodiecko,项目名称:PYTHON_DIST,代码行数:11,代码来源:test_zipimport.py


示例7: test_cache_subdir

    def test_cache_subdir(self):
        import os
        self.writefile('x.py', '')
        self.writefile('sub/__init__.py', '')
        self.writefile('sub/yy.py', '')
        from zipimport import _zip_directory_cache, zipimporter
        sub_importer = zipimporter(self.zipfile + os.path.sep + 'sub')
        main_importer = zipimporter(self.zipfile)

        assert main_importer is not sub_importer
        assert main_importer.prefix == ""
        assert sub_importer.prefix == "sub" + os.path.sep
开发者ID:Darriall,项目名称:pypy,代码行数:12,代码来源:test_zipimport.py


示例8: testZipImporterMethodsInSubDirectory

    def testZipImporterMethodsInSubDirectory(self):
        packdir = TESTPACK + os.sep
        packdir2 = packdir + TESTPACK2 + os.sep
        files = {packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
                 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}

        z = ZipFile(TEMP_ZIP, "w")
        try:
            for name, (mtime, data) in files.items():
                zinfo = ZipInfo(name, time.localtime(mtime))
                zinfo.compress_type = self.compression
                zinfo.comment = b"eggs"
                z.writestr(zinfo, data)
            z.close()

            zi = zipimport.zipimporter(TEMP_ZIP + os.sep + packdir)
            self.assertEqual(zi.archive, TEMP_ZIP)
            self.assertEqual(zi.prefix, packdir)
            self.assertEqual(zi.is_package(TESTPACK2), True)
            mod = zi.load_module(TESTPACK2)
            self.assertEqual(zi.get_filename(TESTPACK2), mod.__file__)

            self.assertEqual(
                zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
            self.assertEqual(
                zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)

            pkg_path = TEMP_ZIP + os.sep + packdir + TESTPACK2
            zi2 = zipimport.zipimporter(pkg_path)
            find_mod_dotted = zi2.find_module(TESTMOD)
            self.assertIsNotNone(find_mod_dotted)
            self.assertIsInstance(find_mod_dotted, zipimport.zipimporter)
            self.assertFalse(zi2.is_package(TESTMOD))
            load_mod = find_mod_dotted.load_module(TESTMOD)
            self.assertEqual(
                find_mod_dotted.get_filename(TESTMOD), load_mod.__file__)

            mod_path = TESTPACK2 + os.sep + TESTMOD
            mod_name = module_path_to_dotted_name(mod_path)
            mod = importlib.import_module(mod_name)
            self.assertTrue(mod_name in sys.modules)
            self.assertEqual(zi.get_source(TESTPACK2), None)
            self.assertEqual(zi.get_source(mod_path), None)
            self.assertEqual(zi.get_filename(mod_path), mod.__file__)
            # To pass in the module name instead of the path, we must use the
            # right importer.
            loader = mod.__loader__
            self.assertEqual(loader.get_source(mod_name), None)
            self.assertEqual(loader.get_filename(mod_name), mod.__file__)
        finally:
            z.close()
            os.remove(TEMP_ZIP)
开发者ID:3lnc,项目名称:cpython,代码行数:52,代码来源:test_zipimport.py


示例9: testFileUnreadable

    def testFileUnreadable(self):
        support.unlink(TESTMOD)
        fd = os.open(TESTMOD, os.O_CREAT, 000)
        try:
            os.close(fd)

            with self.assertRaises(zipimport.ZipImportError) as cm:
                zipimport.zipimporter(TESTMOD)
        finally:
            # If we leave "the read-only bit" set on Windows, nothing can
            # delete TESTMOD, and later tests suffer bogus failures.
            os.chmod(TESTMOD, 0o666)
            support.unlink(TESTMOD)
开发者ID:10sr,项目名称:cpython,代码行数:13,代码来源:test_zipimport.py


示例10: test_good_bad_arguments

 def test_good_bad_arguments(self):
     from zipimport import zipimporter
     import os
     self.writefile("x.py", "y")
     zipimporter(self.zipfile) # should work
     raises(ImportError, "zipimporter(os.path.dirname(self.zipfile))")
     raises(ImportError, 'zipimporter("fsafdetrssffdsagadfsafdssadasa")')
     name = os.path.join(os.path.dirname(self.zipfile), "x.zip")
     f = open(name, "w")
     f.write("zzz")
     f.close()
     raises(ImportError, 'zipimporter(name)')
     # this should work as well :-/
     zipimporter(os.path.join(self.zipfile, 'x'))
开发者ID:Darriall,项目名称:pypy,代码行数:14,代码来源:test_zipimport.py


示例11: register_class

def register_class(m):
    """
    Register module named m, if not already registered
    """

    def log(e):
        mt = isinstance(e, zipimport.ZipImportError) and 'zip ' or ''
        msg = "Couldn't load %smodule %s" % (mt, m)
        logger.notifyChannel('init', netsvc.LOG_CRITICAL, msg)
        logger.notifyChannel('init', netsvc.LOG_CRITICAL, e)

    global loaded
    if m in loaded:
        return
    logger.notifyChannel('init', netsvc.LOG_INFO, 'module %s: registering objects' % m)
    mod_path = get_module_path(m)

    try:
        zip_mod_path = mod_path + '.zip'
        if not os.path.isfile(zip_mod_path):
            fm = imp.find_module(m, ad_paths)
            try:
                imp.load_module(m, *fm)
            finally:
                if fm[0]:
                    fm[0].close()
        else:
            zimp = zipimport.zipimporter(zip_mod_path)
            zimp.load_module(m)
    except Exception, e:
        log(e)
        raise
开发者ID:lcrdcastro,项目名称:viaweb,代码行数:32,代码来源:__init__.py


示例12: _testBogusZipFile

    def _testBogusZipFile(self):
        support.unlink(TESTMOD)
        fp = open(TESTMOD, 'w+')
        fp.write(struct.pack('=I', 0x06054B50))
        fp.write('a' * 18)
        fp.close()
        z = zipimport.zipimporter(TESTMOD)

        try:
            self.assertRaises(TypeError, z.find_module, None)
            self.assertRaises(TypeError, z.load_module, None)
            self.assertRaises(TypeError, z.is_package, None)
            self.assertRaises(TypeError, z.get_code, None)
            self.assertRaises(TypeError, z.get_data, None)
            self.assertRaises(TypeError, z.get_source, None)

            error = zipimport.ZipImportError
            self.assertEqual(z.find_module('abc'), None)

            self.assertRaises(error, z.load_module, 'abc')
            self.assertRaises(error, z.get_code, 'abc')
            self.assertRaises(IOError, z.get_data, 'abc')
            self.assertRaises(error, z.get_source, 'abc')
            self.assertRaises(error, z.is_package, 'abc')
        finally:
            zipimport._zip_directory_cache.clear()
开发者ID:LinkedModernismProject,项目名称:web_code,代码行数:26,代码来源:test_zipimport.py


示例13: LoadPlugins

	def LoadPlugins(self, obj, fileName):
		""" Method which load plugins from zip
			Used for define or redefine method of amd. and .cmd model
			The name of plugin file must be "plugins.py"
		"""
		### if list of activated plugins is not empty
		if obj.plugins != []:
			### import zipfile model
			if zipfile.is_zipfile(fileName):
				importer = zipimport.zipimporter(fileName)
				if importer.find_module('plugins'):

					try:
						module = importer.load_module('plugins')
					except ImportError, info:
						sys.stdout.write("%s\n"%info)
						return info

					for m in [e for e in map(module.__dict__.get, dir(module)) if not inspect.ismodule(e) and inspect.getmodule(e) is module]:
						name = m.__name__
						### import only plugins in plugins list (dynamic attribute)
						if name in obj.plugins:
							try:
								### new object to assaign
								new = eval("module.%s"%name)
								if inspect.isfunction(new):
									setattr(obj, name, types.MethodType(new, obj))
								elif inspect.isclass(new):
									### TODO: monkey patchin !!! (most simple is to change python file for override class)
									pass

							except Exception, info:
								sys.stdout.write(_('plugins %s not loaded : %s\n'%(name,info)))
								return info
开发者ID:AsmaDhanePersonal,项目名称:DEVSimPy,代码行数:34,代码来源:Savable.py


示例14: ziploader

 def ziploader(*paths):
     """Obtain a zipimporter for a directory under the main zip."""
     path = os.path.join(loader.archive, *paths)
     zl = sys.path_importer_cache.get(path)
     if not zl:
         zl = zipimport.zipimporter(path)
     return zl
开发者ID:Distrotech,项目名称:mercurial,代码行数:7,代码来源:__init__.py


示例15: testZipImporterMethodsInSubDirectory

    def testZipImporterMethodsInSubDirectory(self):
        packdir = TESTPACK + os.sep
        packdir2 = packdir + TESTPACK2 + os.sep
        files = {packdir2 + "__init__" + pyc_ext: (NOW, test_pyc),
                 packdir2 + TESTMOD + pyc_ext: (NOW, test_pyc)}

        z = ZipFile(TEMP_ZIP, "w")
        try:
            for name, (mtime, data) in files.items():
                zinfo = ZipInfo(name, time.localtime(mtime))
                zinfo.compress_type = self.compression
                z.writestr(zinfo, data)
            z.close()

            zi = zipimport.zipimporter(TEMP_ZIP + os.sep + packdir)
            self.assertEquals(zi.archive, TEMP_ZIP)
            self.assertEquals(zi.prefix, packdir)
            self.assertEquals(zi.is_package(TESTPACK2), True)
            zi.load_module(TESTPACK2)

            self.assertEquals(zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
            self.assertEquals(zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)

            mod_name = TESTPACK2 + os.sep + TESTMOD
            mod = __import__(module_path_to_dotted_name(mod_name))
            self.assertEquals(zi.get_source(TESTPACK2), None)
            self.assertEquals(zi.get_source(mod_name), None)
        finally:
            z.close()
            os.remove(TEMP_ZIP)
开发者ID:LinkedModernismProject,项目名称:web_code,代码行数:30,代码来源:test_zipimport.py


示例16: instance

    def instance(self, parameters, parent=None, address=None):
        # if no absolute path is given im mod-meta -> take it relative to the
        # meta-file
        mod_archive = self.getArchive()
        if not os.path.isabs(mod_archive):
            mod_archive = os.path.join( os.path.dirname(self._d_file_path), mod_archive)
         
        # try to find module:
        zipimp = zipimporter(mod_archive);
        mod = zipimp.load_module(self.getClass());
 
        #load class from module
        try:
            cls = mod.__dict__[self.getClass()]
        except:
            raise ItemNotFound("Can't find class %s in %s [%s]"%
                        (self.getClass(), mod_archive, mod.__dict__.keys()))

        #instance class:
        if not issubclass(cls, (CInnerModule,CDisposableModule)):
            self._d_logger.debug("Module %s instance with params %s"%(self.getClass(),parameters))
            return cls(parameters)
        else:
            self._d_logger.debug("InnerModule %s instance with addr %s and params %s"%(self.getClass(), address, parameters))
            return cls(parent, address, parameters)
开发者ID:BackupTheBerlios,项目名称:pplt-svn,代码行数:25,代码来源:CoreModuleMeta.py


示例17: download

 def download(self, cr, uid, ids, download=True, context=None):
     res = []
     for mod in self.browse(cr, uid, ids, context=context):
         if not mod.url:
             continue
         match = re.search('-([a-zA-Z0-9\._-]+)(\.zip)', mod.url, re.I)
         version = '0'
         if match:
             version = match.group(1)
         if parse_version(mod.installed_version or '0') >= parse_version(version):
             continue
         res.append(mod.url)
         if not download:
             continue
         zip_content = urllib.urlopen(mod.url).read()
         fname = addons.get_module_path(str(mod.name)+'.zip', downloaded=True)
         try:
             with open(fname, 'wb') as fp:
                 fp.write(zip_content)
         except Exception:
             _logger.exception('Error when trying to create module '
                               'file %s', fname)
             raise orm.except_orm(_('Error'), _('Can not create the module file:\n %s') % (fname,))
         terp = self.get_module_info(mod.name)
         self.write(cr, uid, mod.id, self.get_values_from_terp(terp))
         cr.execute('DELETE FROM ir_module_module_dependency ' \
                 'WHERE module_id = %s', (mod.id,))
         self._update_dependencies(cr, uid, mod, terp.get('depends',
             []))
         self._update_category(cr, uid, mod, terp.get('category',
             'Uncategorized'))
         # Import module
         zimp = zipimport.zipimporter(fname)
         zimp.load_module(mod.name)
     return res
开发者ID:Aravinthu,项目名称:openerp-server-6.1,代码行数:35,代码来源:module.py


示例18: load_openerp_module

def load_openerp_module(module_name):
    """ Load an PengERP module, if not already loaded.

    This loads the module and register all of its models, thanks to either
    the MetaModel metaclass, or the explicit instantiation of the model.
    This is also used to load server-wide module (i.e. it is also used
    when there is no model to register).
    """
    global loaded
    if module_name in loaded:
        return

    initialize_sys_path()
    try:
        mod_path = get_module_path(module_name)
        zip_mod_path = '' if not mod_path else mod_path + '.zip'
        if not os.path.isfile(zip_mod_path):
            __import__('openerp.addons.' + module_name)
        else:
            zimp = zipimport.zipimporter(zip_mod_path)
            zimp.load_module(module_name)

        # Call the module's post-load hook. This can done before any model or
        # data has been initialized. This is ok as the post-load hook is for
        # server-wide (instead of registry-specific) functionalities.
        info = load_information_from_description_file(module_name)
        if info['post_load']:
            getattr(sys.modules['openerp.addons.' + module_name], info['post_load'])()

    except Exception, e:
        mt = isinstance(e, zipimport.ZipImportError) and 'zip ' or ''
        msg = "Couldn't load %smodule %s" % (mt, module_name)
        _logger.critical(msg)
        _logger.critical(e)
        raise
开发者ID:ccdos,项目名称:OpenERP,代码行数:35,代码来源:module.py


示例19: dist_from_egg

def dist_from_egg(egg_path):
  if os.path.isdir(egg_path):
    metadata = PathMetadata(egg_path, os.path.join(egg_path, 'EGG-INFO'))
  else:
    # Assume it's a file or an internal egg
    metadata = EggMetadata(zipimporter(egg_path))
  return Distribution.from_filename(egg_path, metadata=metadata)
开发者ID:jfarrell,项目名称:commons,代码行数:7,代码来源:translator.py


示例20: module_list

def module_list(path):
    """
    Return the list containing the names of the modules available in the given
    folder.
    """
    # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
    if path == '':
        path = '.'

    if os.path.isdir(path):
        folder_list = os.listdir(path)
    elif path.endswith('.egg'):
        try:
            folder_list = [f for f in zipimporter(path)._files]
        except:
            folder_list = []
    else:
        folder_list = []

    if not folder_list:
        return []

    # A few local constants to be used in loops below
    isfile = os.path.isfile
    pjoin = os.path.join
    basename = os.path.basename

    # Now find actual path matches for packages or modules
    folder_list = [p for p in folder_list
                   if isfile(pjoin(path, p,'__init__.py'))
                   or import_re.match(p) ]

    return [basename(p).split('.')[0] for p in folder_list]
开发者ID:linxiulei,项目名称:web_robot,代码行数:33,代码来源:completerlib.py



注:本文中的zipimport.zipimporter函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python zipline.TradingAlgorithm类代码示例发布时间:2022-05-26
下一篇:
Python zipfile.ZipInfo类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap