本文整理匯總了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
示例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
示例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
示例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)
示例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()
示例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
示例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)
示例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)
示例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
示例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))
示例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)
示例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
示例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