当前位置: 首页>>代码示例>>Python>>正文


Python imp.get_magic方法代码示例

本文整理汇总了Python中imp.get_magic方法的典型用法代码示例。如果您正苦于以下问题:Python imp.get_magic方法的具体用法?Python imp.get_magic怎么用?Python imp.get_magic使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在imp的用法示例。


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

示例1: importfile

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def importfile(path):
    """Import a Python source file or compiled file given its path."""
    magic = imp.get_magic()
    with open(path, 'rb') as file:
        if file.read(len(magic)) == magic:
            kind = imp.PY_COMPILED
        else:
            kind = imp.PY_SOURCE
        file.seek(0)
        filename = os.path.basename(path)
        name, ext = os.path.splitext(filename)
        try:
            module = imp.load_module(name, file, path, (ext, 'r', kind))
        except:
            raise ErrorDuringImport(path, sys.exc_info())
    return module 
开发者ID:war-and-code,项目名称:jawfish,代码行数:18,代码来源:pydoc.py

示例2: importfile

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def importfile(path):
    """Import a Python source file or compiled file given its path."""
    magic = imp.get_magic()
    file = open(path, 'r')
    if file.read(len(magic)) == magic:
        kind = imp.PY_COMPILED
    else:
        kind = imp.PY_SOURCE
    file.close()
    filename = os.path.basename(path)
    name, ext = os.path.splitext(filename)
    file = open(path, 'r')
    try:
        module = imp.load_module(name, file, path, (ext, 'r', kind))
    except:
        raise ErrorDuringImport(path, sys.exc_info())
    file.close()
    return module 
开发者ID:glmcdona,项目名称:meddle,代码行数:20,代码来源:pydoc.py

示例3: load_compiled

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def load_compiled(self, name, filename, code, ispackage = False):
		#if data[:4] != imp.get_magic():
		#	raise ImportError('Bad magic number in %s' % filename)
		# Ignore timestamp in data[4:8]
		#code = marshal.loads(data[8:])
		imp.acquire_lock() # Required in threaded applications

		try:
			mod = imp.new_module(name)
			sys.modules[name] = mod 	# To handle circular and submodule imports
										# it should come before exec.
			try:
				mod.__file__ = filename # Is not so important.
				# For package you have to set mod.__path__ here.
				# Here I handle simple cases only.
				if ispackage:
					mod.__path__ = [name.replace('.', '/')]
				exec(code in mod.__dict__)
			except:
				del sys.modules[name]
				raise
		finally:
			imp.release_lock()

		return mod 
开发者ID:turingsec,项目名称:marsnake,代码行数:27,代码来源:factory_module.py

示例4: load

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def load():
    supportedMagicNumbers = ['03f30d0a', 'd1f20d0a']

    try:
        magicNumberOfThisVersion = imp.get_magic().encode('hex')
        if magicNumberOfThisVersion in supportedMagicNumbers:
            pathToThisVersion = "python/mamoworld/mochaImportPlus/version_" + magicNumberOfThisVersion
            nuke.pluginAddPath(pathToThisVersion)
        else:
            raise Exception(
                "MochaImport+ for NUKE: unsupported version of Python:" + sys.version + "(magic number:" + magicNumberOfThisVersion + ")")

    except Exception as e:
        import traceback
        nuke.tprint(traceback.format_exc())  # Just in case
        msg = 'ERROR: %s' % e
        if nuke.GUI:
            nuke.message(msg)
        else:
            nuke.tprint(msg) 
开发者ID:weijer,项目名称:NukeToolSet,代码行数:22,代码来源:loadMochaImport.py

示例5: output_pyc

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def output_pyc(code, buffer=sys.stdout.buffer):
    import marshal
    import struct
    import time

    if GE_PYTHON_34:
        from importlib.util import MAGIC_NUMBER
    else:
        import imp
        MAGIC_NUMBER = imp.get_magic()

    buffer.write(MAGIC_NUMBER)
    timestamp = struct.pack('i', int(time.time()))
    buffer.write(timestamp)
    if GE_PYTHON_33:
        buffer.write(b'0' * 4)
    marshal.dump(code, buffer)
    buffer.flush() 
开发者ID:i2y,项目名称:mochi,代码行数:20,代码来源:main.py

示例6: load_module

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def load_module(self, fqname, fp, pathname, file_info):
        suffix, mode, type = file_info
        self.msgin(2, "load_module", fqname, fp and "fp", pathname)
        if type == imp.PKG_DIRECTORY:
            m = self.load_package(fqname, pathname)
            self.msgout(2, "load_module ->", m)
            return m
        if type == imp.PY_SOURCE:
            co = compile(fp.read()+'\n', pathname, 'exec')
        elif type == imp.PY_COMPILED:
            if fp.read(4) != imp.get_magic():
                self.msgout(2, "raise ImportError: Bad magic number", pathname)
                raise ImportError, "Bad magic number in %s" % pathname
            fp.read(4)
            co = marshal.load(fp)
        else:
            co = None
        m = self.add_module(fqname)
        m.__file__ = pathname
        if co:
            if self.replace_paths:
                co = self.replace_paths_in_code(co)
            m.__code__ = co
            self.scan_code(co, m)
        self.msgout(2, "load_module ->", m)
        return m 
开发者ID:glmcdona,项目名称:meddle,代码行数:28,代码来源:modulefinder.py

示例7: read_code

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def read_code(stream):
    # This helper is needed in order for the PEP 302 emulation to
    # correctly handle compiled files
    import marshal

    magic = stream.read(4)
    if magic != imp.get_magic():
        return None

    stream.read(4) # Skip timestamp
    return marshal.load(stream) 
开发者ID:glmcdona,项目名称:meddle,代码行数:13,代码来源:pkgutil.py

示例8: test_magic_number

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def test_magic_number(self):
        """
        Each python minor release should generally have a MAGIC_NUMBER
        that does not change once the release reaches candidate status.

        Once a release reaches candidate status, the value of the constant
        EXPECTED_MAGIC_NUMBER in this test should be changed.
        This test will then check that the actual MAGIC_NUMBER matches
        the expected value for the release.

        In exceptional cases, it may be required to change the MAGIC_NUMBER
        for a maintenance release. In this case the change should be
        discussed in python-dev. If a change is required, community
        stakeholders such as OS package maintainers must be notified
        in advance. Such exceptional releases will then require an
        adjustment to this test case.
        """
        EXPECTED_MAGIC_NUMBER = 62211
        raw_magic = imp.get_magic()
        actual = (ord(raw_magic[1]) << 8) + ord(raw_magic[0])

        msg = (
            "To avoid breaking backwards compatibility with cached bytecode "
            "files that can't be automatically regenerated by the current "
            "user, candidate and final releases require the current  "
            "importlib.util.MAGIC_NUMBER to match the expected "
            "magic number in this test. Set the expected "
            "magic number in this test to the current MAGIC_NUMBER to "
            "continue with the release.\n\n"
            "Changing the MAGIC_NUMBER for a maintenance release "
            "requires discussion in python-dev and notification of "
            "community stakeholders."
        )
        self.assertEqual(EXPECTED_MAGIC_NUMBER, actual)#, msg) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:36,代码来源:test_import_magic.py

示例9: data

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def data(self):
        with open(self.bc_path, 'rb') as file:
            data = file.read(8)
        mtime = int(os.stat(self.source_path).st_mtime)
        compare = struct.pack('<4sl', imp.get_magic(), mtime)
        return data, compare 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:8,代码来源:test_compileall.py

示例10: test_mtime

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def test_mtime(self):
        # Test a change in mtime leads to a new .pyc.
        self.recreation_check(struct.pack('<4sl', imp.get_magic(), 1)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:5,代码来源:test_compileall.py

示例11: test_imp_basic

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def test_imp_basic(self):
        magic = imp.get_magic()
        suffixes = imp.get_suffixes()
        self.assertTrue(isinstance(suffixes, list))
        for suffix in suffixes:
            self.assertTrue(isinstance(suffix, tuple))
            self.assertEqual(len(suffix), 3)
        self.assertTrue((".py", "U", 1) in suffixes) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:10,代码来源:test_imp.py

示例12: write

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def write(self):
    """
      Persists the changes in the bytecode. This overwrites the current file that
      contains the bytecode with the new bytecode while preserving the timestamp.

      Note that the magic number if changed to be the one from the current Python
      version that runs the instrumentation process.
    """
    if not self.has_changes:
      logger.debug("Skip writing %s, no changes detected.", self.main_module.module_path)
      return

    try:
      new_co = self.main_module.code_object

      # Always keep the changed time from the source
      source_file = self.main_module.module_path.replace('.pyc', '.py')
      timestamp = self.modif_date
      try:
        timestamp = long(os.stat(source_file).st_mtime)
      except:
        pass
      fd = open(self.main_module.module_path, 'wb')
      fd.write('\0\0\0\0') # Magic placeholder
      fd.write(struct.pack('<l', timestamp))
      marshal.dump(new_co, fd)
      fd.flush()
      fd.seek(0, 0)
      fd.write(imp.get_magic())
      fd.close()
      logger.debug("Wrote file %s", self.main_module.module_path)
      return True
    except Exception, ex:
      logger.error("Exception- %s", str(ex))
      logger.error("\n%s", traceback.format_exc())
      return False 
开发者ID:neuroo,项目名称:equip,代码行数:38,代码来源:code.py

示例13: make_pyc

# 需要导入模块: import imp [as 别名]
# 或者: from imp import get_magic [as 别名]
def make_pyc(co, mtime):
    data = marshal.dumps(co)
    if type(mtime) is type(0.0):
        # Mac mtimes need a bit of special casing
        if mtime < 0x7fffffff:
            mtime = int(mtime)
        else:
            mtime = int(-0x100000000L + long(mtime))
    pyc = imp.get_magic() + struct.pack("<i", int(mtime)) + data
    return pyc 
开发者ID:dxwu,项目名称:BinderFilter,代码行数:12,代码来源:test_zipimport.py


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