本文整理匯總了Python中imp.PY_SOURCE屬性的典型用法代碼示例。如果您正苦於以下問題:Python imp.PY_SOURCE屬性的具體用法?Python imp.PY_SOURCE怎麽用?Python imp.PY_SOURCE使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類imp
的用法示例。
在下文中一共展示了imp.PY_SOURCE屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: importfile
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [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: find_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def find_module(self, fullname, path=None):
logger.debug('Running find_module: {0}...'.format(fullname))
if '.' in fullname:
parent, child = fullname.rsplit('.', 1)
if path is None:
loader = self.find_module(parent, path)
mod = loader.load_module(parent)
path = mod.__path__
fullname = child
# Perhaps we should try using the new importlib functionality in Python
# 3.3: something like this?
# thing = importlib.machinery.PathFinder.find_module(fullname, path)
try:
self.found = imp.find_module(fullname, path)
except Exception as e:
logger.debug('Py2Fixer could not find {0}')
logger.debug('Exception was: {0})'.format(fullname, e))
return None
self.kind = self.found[-1][-1]
if self.kind == imp.PKG_DIRECTORY:
self.pathname = os.path.join(self.found[1], '__init__.py')
elif self.kind == imp.PY_SOURCE:
self.pathname = self.found[1]
return self
示例3: __init__
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def __init__(self, name, loadfile):
"""
Load a single plugin
:param name: module name
:param loadfile: the main .py file
:raises Exception: Typically ImportError or OSError
"""
self.name = name # Display name.
self.folder = name # basename of plugin folder. None for internal plugins.
self.module = None # None for disabled plugins.
if loadfile:
sys.stdout.write(('loading plugin %s from "%s"\n' % (name.replace('.', '_'), loadfile)).encode('utf-8'))
with open(loadfile, 'rb') as plugfile:
module = imp.load_module('plugin_%s' % name.encode('ascii', 'replace').replace('.', '_'), plugfile, loadfile.encode(sys.getfilesystemencoding()),
('.py', 'r', imp.PY_SOURCE))
if module.plugin_start.func_code.co_argcount == 0:
newname = module.plugin_start()
else:
newname = module.plugin_start(os.path.dirname(loadfile))
self.name = newname and unicode(newname) or name
self.module = module
else:
sys.stdout.write('plugin %s disabled\n' % name)
示例4: importfile
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [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
示例5: get_source
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def get_source(self, fullname=None):
fullname = self._fix_name(fullname)
if self.source is None:
mod_type = self.etc[2]
if mod_type==imp.PY_SOURCE:
self._reopen()
try:
self.source = self.file.read()
finally:
self.file.close()
elif mod_type==imp.PY_COMPILED:
if os.path.exists(self.filename[:-1]):
f = open(self.filename[:-1], 'rU')
self.source = f.read()
f.close()
elif mod_type==imp.PKG_DIRECTORY:
self.source = self._get_delegate().get_source()
return self.source
示例6: load_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def load_module(self, name, stuff):
file, filename, info = stuff
(suff, mode, type) = info
try:
if type == BUILTIN_MODULE:
return self.hooks.init_builtin(name)
if type == FROZEN_MODULE:
return self.hooks.init_frozen(name)
if type == C_EXTENSION:
m = self.hooks.load_dynamic(name, filename, file)
elif type == PY_SOURCE:
m = self.hooks.load_source(name, filename, file)
elif type == PY_COMPILED:
m = self.hooks.load_compiled(name, filename, file)
elif type == PKG_DIRECTORY:
m = self.hooks.load_package(name, filename, file)
else:
raise ImportError, "Unrecognized module type (%r) for %s" % \
(type, name)
finally:
if file: file.close()
m.__file__ = filename
return m
示例7: test_imp_module
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def test_imp_module(self):
self.write_to_file(self._f_module, "value = 'imp test module'")
pf, pp, (px, pm, pt) = imp.find_module("imptestmod", [self._imptestdir])
self.assertEqual(pt, imp.PY_SOURCE)
self.assertTrue(pf != None)
self.assertTrue(isinstance(pf, file))
module = imp.load_module("imptestmod", pf, pp, (px, pm, pt))
self.assertEqual(module.value, 'imp test module')
pf.close()
with path_modifier(self._imptestdir) as p:
fm = imp.find_module("imptestmod")
# unpack the result obtained above
pf, pp, (px, pm, pt) = fm
self.assertEqual(pt, imp.PY_SOURCE)
self.assertTrue(pf != None)
self.assertTrue(isinstance(pf, file))
self.assertEqual(px, ".py")
self.assertEqual(pm, "U")
module = imp.load_module("imptestmod", pf, pp, (px, pm, pt))
self.assertEqual(module.value, 'imp test module')
pf.close()
示例8: _visit_pyfiles
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def _visit_pyfiles(list, dirname, names):
"""Helper for getFilesForName()."""
# get extension for python source files
if not globals().has_key('_py_ext'):
global _py_ext
_py_ext = [triple[0] for triple in imp.get_suffixes()
if triple[2] == imp.PY_SOURCE][0]
# don't recurse into CVS directories
if 'CVS' in names:
names.remove('CVS')
# add all *.py files to list
list.extend(
[os.path.join(dirname, file) for file in names
if os.path.splitext(file)[1] == _py_ext]
)
示例9: get_code
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def get_code(self, fullname=None):
fullname = self._fix_name(fullname)
if self.code is None:
mod_type = self.etc[2]
if mod_type==imp.PY_SOURCE:
source = self.get_source(fullname)
self.code = compile(source, self.filename, 'exec')
elif mod_type==imp.PY_COMPILED:
self._reopen()
try:
self.code = read_code(self.file)
finally:
self.file.close()
elif mod_type==imp.PKG_DIRECTORY:
self.code = self._get_delegate().get_code()
return self.code
示例10: _spec_from_modpath
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def _spec_from_modpath(modpath, path=None, context=None):
"""given a mod path (i.e. split module / package name), return the
corresponding spec
this function is used internally, see `file_from_modpath`'s
documentation for more information
"""
assert modpath
location = None
if context is not None:
try:
found_spec = spec.find_spec(modpath, [context])
location = found_spec.location
except ImportError:
found_spec = spec.find_spec(modpath, path)
location = found_spec.location
else:
found_spec = spec.find_spec(modpath, path)
if found_spec.type == spec.ModuleType.PY_COMPILED:
try:
location = get_source_file(found_spec.location)
return found_spec._replace(location=location, type=spec.ModuleType.PY_SOURCE)
except NoSourceFile:
return found_spec._replace(location=location)
elif found_spec.type == spec.ModuleType.C_BUILTIN:
# integrated builtin module
return found_spec._replace(location=None)
elif found_spec.type == spec.ModuleType.PKG_DIRECTORY:
location = _has_init(found_spec.location)
return found_spec._replace(location=location, type=spec.ModuleType.PY_SOURCE)
return found_spec
示例11: test_accessible
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def test_accessible(self):
imp.find_module('bar', ['foo']).AndReturn((None, 'foo/bar.py',
(None, None, imp.PY_SOURCE)))
stubs.FakeFile.is_file_accessible('foo/bar.py').AndReturn(True)
self.mox.ReplayAll()
self.assertIsNone(self.hook.find_module('foo.bar', ['foo']))
示例12: test_not_accessible
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def test_not_accessible(self):
imp.find_module('bar', ['foo']).AndReturn((None, 'foo/bar.py',
(None, None, imp.PY_SOURCE)))
stubs.FakeFile.is_file_accessible('foo/bar.py').AndReturn(False)
self.mox.ReplayAll()
self.assertEqual(self.hook, self.hook.find_module('foo.bar', ['foo']))
示例13: test_enabled_c_library
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def test_enabled_c_library(self):
imp.find_module('lxmla', ['foo']).AndReturn((None, 'lxmla.py',
(None, None, imp.PY_SOURCE)))
stubs.FakeFile.is_file_accessible('lxmla.py').AndReturn(False)
self.mox.ReplayAll()
self.assertEqual(self.hook, self.hook.find_module('lxmla', ['foo']))
self.assertIsNone(self.hook.find_module('lxml', None))
self.assertIsNone(self.hook.find_module('lxml.html', None))
示例14: get_module_constant
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [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)
示例15: _get_codeobj
# 需要導入模塊: import imp [as 別名]
# 或者: from imp import PY_SOURCE [as 別名]
def _get_codeobj(pyfile):
""" Returns the code object, given a python file """
from imp import PY_COMPILED, PY_SOURCE
result, fileobj, fullpath = _check_if_pyc(pyfile)
# WARNING:
# fp.read() can blowup if the module is extremely large file.
# Lookout for overflow errors.
try:
data = fileobj.read()
finally:
fileobj.close()
# This is a .pyc file. Treat accordingly.
if result is PY_COMPILED:
# .pyc format is as follows:
# 0 - 4 bytes: Magic number, which changes with each create of .pyc file.
# First 2 bytes change with each marshal of .pyc file. Last 2 bytes is "\r\n".
# 4 - 8 bytes: Datetime value, when the .py was last changed.
# 8 - EOF: Marshalled code object data.
# So to get code object, just read the 8th byte onwards till EOF, and
# UN-marshal it.
import marshal
code_obj = marshal.loads(data[8:])
elif result is PY_SOURCE:
# This is a .py file.
code_obj = compile(data, fullpath, 'exec')
else:
# Unsupported extension
raise Exception("Input file is unknown format: {0}".format(fullpath))
# Return code object
return code_obj