本文整理汇总了Python中marshal.load方法的典型用法代码示例。如果您正苦于以下问题:Python marshal.load方法的具体用法?Python marshal.load怎么用?Python marshal.load使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类marshal
的用法示例。
在下文中一共展示了marshal.load方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_bytecode
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def load_bytecode(self, f):
"""Loads bytecode from a file or file like object."""
# make sure the magic header is correct
magic = f.read(len(bc_magic))
if magic != bc_magic:
self.reset()
return
# the source code of the file changed, we need to reload
checksum = pickle.load(f)
if self.checksum != checksum:
self.reset()
return
# if marshal_load fails then we need to reload
try:
self.code = marshal_load(f)
except (EOFError, ValueError, TypeError):
self.reset()
return
示例2: load_stats
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def load_stats(self, arg):
if not arg: self.stats = {}
elif isinstance(arg, basestring):
f = open(arg, 'rb')
self.stats = marshal.load(f)
f.close()
try:
file_stats = os.stat(arg)
arg = time.ctime(file_stats.st_mtime) + " " + arg
except: # in case this is not unix
pass
self.files = [ arg ]
elif hasattr(arg, 'create_stats'):
arg.create_stats()
self.stats = arg.stats
arg.stats = {}
if not self.stats:
raise TypeError, "Cannot create or construct a %r object from '%r''" % (
self.__class__, arg)
return
示例3: __init__
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def __init__(self, fs_imp=None):
# we're definitely going to be importing something in the future,
# so let's just load the OS-related facilities.
if not _os_stat:
_os_bootstrap()
# This is the Importer that we use for grabbing stuff from the
# filesystem. It defines one more method (import_from_dir) for our use.
if fs_imp is None:
cls = self.clsFilesystemImporter or _FilesystemImporter
fs_imp = cls()
self.fs_imp = fs_imp
# Initialize the set of suffixes that we recognize and import.
# The default will import dynamic-load modules first, followed by
# .py files (or a .py file's cached bytecode)
for desc in imp.get_suffixes():
if desc[2] == imp.C_EXTENSION:
self.add_suffix(desc[0],
DynLoadSuffixImporter(desc).import_file)
self.add_suffix('.py', py_suffix_importer)
示例4: _import_one
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def _import_one(self, parent, modname, fqname):
"Import a single module."
# has the module already been imported?
try:
return sys.modules[fqname]
except KeyError:
pass
# load the module's code, or fetch the module itself
result = self.get_code(parent, modname, fqname)
if result is None:
return None
module = self._process_result(result, fqname)
# insert the module into its parent
if parent:
setattr(parent, modname, module)
return module
示例5: get_code
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def get_code(self, parent, modname, fqname):
if parent:
# these modules definitely do not occur within a package context
return None
# look for the module
if imp.is_builtin(modname):
type = imp.C_BUILTIN
elif imp.is_frozen(modname):
type = imp.PY_FROZEN
else:
# not found
return None
# got it. now load and return it.
module = imp.load_module(modname, None, modname, ('', '', type))
return 0, module, { }
######################################################################
#
# Internal importer used for importing from the filesystem
#
示例6: py_suffix_importer
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def py_suffix_importer(filename, finfo, fqname):
file = filename[:-3] + _suffix
t_py = long(finfo[8])
t_pyc = _timestamp(file)
code = None
if t_pyc is not None and t_pyc >= t_py:
f = open(file, 'rb')
if f.read(4) == imp.get_magic():
t = struct.unpack('<I', f.read(4))[0]
if t == t_py:
code = marshal.load(f)
f.close()
if code is None:
file = filename
code = _compile(file, t_py)
return 0, code, { '__file__' : file }
示例7: load_stats
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def load_stats(self, arg):
if not arg: self.stats = {}
elif isinstance(arg, basestring):
f = open(arg, 'rb')
self.stats = marshal.load(f)
f.close()
try:
file_stats = os.stat(arg)
arg = time.ctime(file_stats.st_mtime) + " " + arg
except: # in case this is not unix
pass
self.files = [ arg ]
elif hasattr(arg, 'create_stats'):
arg.create_stats()
self.stats = arg.stats
arg.stats = {}
if not self.stats:
raise TypeError("Cannot create or construct a %r object from %r"
% (self.__class__, arg))
return
示例8: test_foreign_code
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def test_foreign_code(self):
py_compile.compile(self.file_name)
with open(self.compiled_name, "rb") as f:
header = f.read(8)
code = marshal.load(f)
constants = list(code.co_consts)
foreign_code = test_main.func_code
pos = constants.index(1)
constants[pos] = foreign_code
code = type(code)(code.co_argcount, code.co_nlocals, code.co_stacksize,
code.co_flags, code.co_code, tuple(constants),
code.co_names, code.co_varnames, code.co_filename,
code.co_name, code.co_firstlineno, code.co_lnotab,
code.co_freevars, code.co_cellvars)
with open(self.compiled_name, "wb") as f:
f.write(header)
marshal.dump(code, f)
mod = self.import_module()
self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)
示例9: test_recursion_limit
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def test_recursion_limit(self):
# Create a deeply nested structure.
head = last = []
# The max stack depth should match the value in Python/marshal.c.
if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
MAX_MARSHAL_STACK_DEPTH = 1000
else:
MAX_MARSHAL_STACK_DEPTH = 2000
for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
last.append([0])
last = last[-1]
# Verify we don't blow out the stack with dumps/load.
data = marshal.dumps(head)
new_head = marshal.loads(data)
# Don't use == to compare objects, it can exceed the recursion limit.
self.assertEqual(len(new_head), len(head))
self.assertEqual(len(new_head[0]), len(head[0]))
self.assertEqual(len(new_head[-1]), len(head[-1]))
last.append([0])
self.assertRaises(ValueError, marshal.dumps, head)
示例10: test_file_multiple_reads
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def test_file_multiple_reads(self):
"""calling load w/ a file should only advance the length of the file"""
l = []
for i in xrange(10):
l.append(marshal.dumps({i:i}))
data = ''.join(l)
with open('tempfile.txt', 'w') as f:
f.write(data)
with open('tempfile.txt') as f:
for i in xrange(10):
obj = marshal.load(f)
self.assertEqual(obj, {i:i})
self.delete_files('tempfile.txt')
示例11: test_imp_module
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def test_imp_module(self):
# Verify that the imp module can correctly load and find .py files
# XXX (ncoghlan): It would be nice to use test_support.CleanImport
# here, but that breaks because the os module registers some
# handlers in copy_reg on import. Since CleanImport doesn't
# revert that registration, the module is left in a broken
# state after reversion. Reinitialising the module contents
# and just reverting os.environ to its previous state is an OK
# workaround
orig_path = os.path
orig_getenv = os.getenv
with EnvironmentVarGuard():
x = imp.find_module("os")
new_os = imp.load_module("os", *x)
self.assertIs(os, new_os)
self.assertIs(orig_path, new_os.path)
self.assertIsNot(orig_getenv, new_os.getenv)
示例12: marshal_load
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def marshal_load(f):
if isinstance(f, file):
return marshal.load(f)
return marshal.loads(f.read())
示例13: getCompiledfileDisassembled
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def getCompiledfileDisassembled(pycPath, pyPath, optimization,
forBuffer=False):
"""Reads the .pyc file and provides the plain text disassembly"""
pycFile = open(pycPath, 'rb')
magic = pycFile.read(4)
timestamp = pycFile.read(4)
size = None
if sys.version_info.major == 3 and sys.version_info.minor >= 3:
size = pycFile.read(4)
size = struct.unpack('I', size)[0]
code = marshal.load(pycFile)
magic = binascii.hexlify(magic).decode('utf-8')
timestamp = time.asctime(
time.localtime(struct.unpack('I', b'D\xa5\xc2X')[0]))
bufferSpec = ''
if forBuffer:
bufferSpec = ' (unsaved buffer)'
return '\n'.join(
['-' * 80,
'Python version: ' + platform.python_version(),
'Python interpreter path: ' + sys.executable,
'Interpreter magic: ' + magic,
'Interpreter timestamp: ' + timestamp,
'Python module: ' + pyPath + bufferSpec,
'Optimization: ' + optToString(optimization),
'Code size: ' + str(size),
'-' * 80,
recursiveDisassembly(code)])
示例14: get_module_constant
# 需要导入模块: import marshal [as 别名]
# 或者: from marshal import load [as 别名]
def get_module_constant(module, symbol, default=-1, paths=None):
"""Find 'module' by searching 'paths', and extract 'symbol'
Return 'None' if 'module' does not exist on 'paths', or it does not define
'symbol'. If the module defines 'symbol' as a constant, return the
constant. Otherwise, return 'default'."""
try:
f, path, (suffix, mode, kind) = find_module(module, paths)
except ImportError:
# Module doesn't exist
return None
try:
if kind==PY_COMPILED:
f.read(8) # skip magic & date
code = marshal.load(f)
elif kind==PY_FROZEN:
code = imp.get_frozen_object(module)
elif kind==PY_SOURCE:
code = compile(f.read(), path, 'exec')
else:
# Not something we can parse; we'll have to import it. :(
if module not in sys.modules:
imp.load_module(module, f, path, (suffix, mode, kind))
return getattr(sys.modules[module], symbol, None)
finally:
if f:
f.close()
return extract_constant(code, symbol, default)