本文整理汇总了Python中types.ModuleType类的典型用法代码示例。如果您正苦于以下问题:Python ModuleType类的具体用法?Python ModuleType怎么用?Python ModuleType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ModuleType类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, env, libs=None):
self.destroyed = False
libs = libs or ['prelude']
for lib in libs:
if 'darwin' in sys.platform:
prelude = join(dirname(realpath(__file__)), lib + '.dylib')
elif 'linux' in sys.platform:
prelude = join(dirname(realpath(__file__)), lib+ '.so')
else:
raise NotImplementedError
# XXX: yeah, don't do this
ctypes._dlopen(prelude, ctypes.RTLD_GLOBAL)
cgen = env['cgen']
self.__namespace = cgen.globals
self.__llmodule = cgen.module
if not detect_avx_support():
tc = le.TargetMachine.new(features='-avx', cm=le.CM_JITDEFAULT)
else:
tc = le.TargetMachine.new(features='', cm=le.CM_JITDEFAULT)
eb = le.EngineBuilder.new(self.__llmodule)
self.__engine = eb.create(tc)
#self.__engine.run_function(cgen.globals['__module'], [])
mod = ModuleType('blir_wrapper')
wrap_llvm_module(cgen.module, self.__engine, mod)
mod.__doc__ = 'Compiled LLVM wrapper module'
self.__mod = mod
开发者ID:aashish24,项目名称:blaze,代码行数:34,代码来源:exc.py
示例2: __strict__
def __strict__(self):
ModuleType.__setattr__(self, "__class__", NormalModule)
if "." in self.__name__:
parent_name, leaf_name = self.__name__.rsplit(".", 1)
parent = sys.modules[parent_name]
setattr(parent, leaf_name, self) # this will __strict__ the parent
reload(self)
开发者ID:pombreda,项目名称:nimp,代码行数:7,代码来源:lazy2.py
示例3: from_config_status
def from_config_status(cls, path):
"""Create an instance from a config.status file."""
code_cache = cls._CODE_CACHE
mtime = os.path.getmtime(path)
# cache the compiled code as it can be reused
# we cache it the first time, or if the file changed
if not path in code_cache or code_cache[path][0] != mtime:
# Add config.status manually to sys.modules so it gets picked up by
# iter_modules_in_path() for automatic dependencies.
mod = ModuleType('config.status')
mod.__file__ = path
sys.modules['config.status'] = mod
with open(path, 'rt') as fh:
source = fh.read()
code_cache[path] = (
mtime,
compile(source, path, 'exec', dont_inherit=1)
)
g = {
'__builtins__': __builtins__,
'__file__': path,
}
l = {}
exec(code_cache[path][1], g, l)
config = BuildConfig()
for name in l['__all__']:
setattr(config, name, l[name])
return config
开发者ID:MichaelKohler,项目名称:gecko-dev,代码行数:34,代码来源:configenvironment.py
示例4: InitPathesAndBuiltins
def InitPathesAndBuiltins():
sys.path.insert(0, eg.mainDir.encode('mbcs'))
sys.path.insert(1, eg.sitePackagesDir.encode('mbcs'))
import cFunctions
sys.modules["eg.cFunctions"] = cFunctions
eg.cFunctions = cFunctions
# add 'wx' to the builtin name space of every module
import __builtin__
__builtin__.wx = wx
# we create a package 'PluginModule' and set its path to the plugin-dir
# so we can simply use __import__ to load a plugin file
corePluginPackage = ModuleType("eg.CorePluginModule")
corePluginPackage.__path__ = [eg.corePluginDir]
sys.modules["eg.CorePluginModule"] = corePluginPackage
eg.CorePluginModule = corePluginPackage
# we create a package 'PluginModule' and set its path to the plugin-dir
# so we can simply use __import__ to load a plugin file
if not os.path.exists(eg.localPluginDir):
os.makedirs(eg.localPluginDir)
userPluginPackage = ModuleType("eg.UserPluginModule")
userPluginPackage.__path__ = [eg.localPluginDir]
sys.modules["eg.UserPluginModule"] = userPluginPackage
eg.UserPluginModule = userPluginPackage
开发者ID:AssetsInc,项目名称:EventGhost,代码行数:26,代码来源:Init.py
示例5: test_get_modpath_all_multi
def test_get_modpath_all_multi(self):
module = ModuleType('nothing')
module.__path__ = ['/path/to/here', '/path/to/there']
self.assertEqual(
indexer.modpath_all(module, None),
['/path/to/here', '/path/to/there'],
)
开发者ID:calmjs,项目名称:calmjs,代码行数:7,代码来源:test_indexer.py
示例6: test_iter_builders_verify_export_target
def test_iter_builders_verify_export_target(self):
mod = ModuleType('calmjs_testing_dummy')
mod.complete = generic_builder
self.addCleanup(sys.modules.pop, 'calmjs_testing_dummy')
sys.modules['calmjs_testing_dummy'] = mod
working_dir = utils.mkdtemp(self)
utils.make_dummy_dist(self, (
('entry_points.txt', '\n'.join([
'[calmjs.artifacts]',
'artifact.js = calmjs_testing_dummy:complete',
'invalid.js = calmjs_testing_dummy:complete',
])),
), 'app', '1.0', working_dir=working_dir)
mock_ws = WorkingSet([working_dir])
class FakeArtifactRegistry(ArtifactRegistry):
def verify_export_target(self, export_target):
return 'invalid.js' not in export_target
registry = FakeArtifactRegistry(
'calmjs.artifacts', _working_set=mock_ws)
# the invalid.js should be filtered out
with pretty_logging(stream=mocks.StringIO()) as stream:
self.assertEqual(1, len(list(registry.iter_builders_for('app'))))
self.assertIn("invalid.js' has been rejected", stream.getvalue())
开发者ID:calmjs,项目名称:calmjs,代码行数:27,代码来源:test_artifact.py
示例7: test_iter_builders_side_effect_build_issue
def test_iter_builders_side_effect_build_issue(self):
mod = ModuleType('calmjs_testing_dummy')
mod.complete = generic_builder
self.addCleanup(sys.modules.pop, 'calmjs_testing_dummy')
sys.modules['calmjs_testing_dummy'] = mod
working_dir = utils.mkdtemp(self)
utils.make_dummy_dist(self, (
('entry_points.txt', '\n'.join([
'[calmjs.artifacts]',
'artifact.js = calmjs_testing_dummy:complete',
])),
), 'app', '1.0', working_dir=working_dir)
mock_ws = WorkingSet([working_dir])
registry = ArtifactRegistry('calmjs.artifacts', _working_set=mock_ws)
registry.update_artifact_metadata('app', {})
root = join(working_dir, 'app-1.0.egg-info', 'calmjs_artifacts')
# clog the build directory so build cannot happen
with open(join(root), 'w'):
pass
ep, toolchain, spec = next(registry.iter_builders_for('app'))
check = []
spec.advise('after_prepare', check.append, True)
with pretty_logging(stream=mocks.StringIO()) as stream:
with self.assertRaises(ToolchainAbort):
toolchain(spec)
self.assertIn(
"an advice in group 'before_prepare' triggered an abort",
stream.getvalue())
# should have stopped at before_prepare
self.assertFalse(check)
开发者ID:calmjs,项目名称:calmjs,代码行数:33,代码来源:test_artifact.py
示例8: test_iter_builders_side_effect
def test_iter_builders_side_effect(self):
# inject dummy module and add cleanup
mod = ModuleType('calmjs_testing_dummy')
mod.complete = generic_builder
self.addCleanup(sys.modules.pop, 'calmjs_testing_dummy')
sys.modules['calmjs_testing_dummy'] = mod
working_dir = utils.mkdtemp(self)
utils.make_dummy_dist(self, (
('entry_points.txt', '\n'.join([
'[calmjs.artifacts]',
'artifact.js = calmjs_testing_dummy:complete',
])),
), 'app', '1.0', working_dir=working_dir)
mock_ws = WorkingSet([working_dir])
registry = ArtifactRegistry('calmjs.artifacts', _working_set=mock_ws)
registry.update_artifact_metadata('app', {})
root = join(working_dir, 'app-1.0.egg-info', 'calmjs_artifacts')
self.assertFalse(exists(root))
ep, toolchain, spec = next(registry.iter_builders_for('app'))
self.assertFalse(exists(root))
# directory only created after the toolchain is executed
toolchain(spec)
self.assertTrue(exists(root))
开发者ID:calmjs,项目名称:calmjs,代码行数:25,代码来源:test_artifact.py
示例9: test_task_dependencies_with_post_definition_injections_custom_names
def test_task_dependencies_with_post_definition_injections_custom_names(self):
import pybuilder.reactor
with patch("pybuilder.reactor.Task"):
@task
def task1():
pass
@task
@depends(task1)
def task2():
pass
@task("task_3")
@depends(task1)
@dependents(task2)
def task3():
pass
module1 = ModuleType("mock_module_one")
module1.task1 = task1
module1.task2 = task2
module2 = ModuleType("mock_module_two")
module2.task3 = task3
self.reactor.collect_tasks_and_actions_and_initializers(module1)
pybuilder.reactor.Task.assert_has_calls([call("task1", task1, [], ''),
call("task2", task2, [TaskDependency(task1)], '')])
self.reactor.collect_tasks_and_actions_and_initializers(module2)
pybuilder.reactor.Task.assert_has_calls([call("task_3", task3, [TaskDependency(task1)], '')])
self.execution_manager.register_late_task_dependencies.assert_has_calls(
[call({}), call({"task2": [TaskDependency("task_3")]})])
开发者ID:wenlien,项目名称:pybuilder,代码行数:34,代码来源:reactor_tests.py
示例10: modify_document
def modify_document(self, doc):
if self.failed:
return
from types import ModuleType
module_name = 'bk_script_' + str(uuid.uuid4()).replace('-', '')
module = ModuleType(module_name)
module.__dict__['__file__'] = abspath(self._path)
# This is to prevent the module from being gc'd before the
# document is. A symptom of a gc'd module is that its
# globals become None.
if not hasattr(doc, '_ScriptHandler__modules'):
setattr(doc, '_ScriptHandler__modules', [])
doc.__modules.append(module)
old_doc = curdoc()
set_curdoc(doc)
old_io = self._monkeypatch_io()
try:
exec(self._code, module.__dict__)
newdoc = curdoc()
# script is supposed to edit the doc not replace it
if newdoc is not doc:
raise RuntimeError("Script at '%s' replaced the output document" % (self._path))
except Exception as e:
self._failed = True
import traceback
self._error_detail = traceback.format_exc()
exc_type, exc_value, exc_traceback = sys.exc_info()
filename, line_number, func, txt = traceback.extract_tb(exc_traceback)[-1]
self._error = "%s\nFile \"%s\", line %d, in %s:\n%s" % (str(e), os.path.basename(filename), line_number, func, txt)
finally:
self._unmonkeypatch_io(old_io)
set_curdoc(old_doc)
开发者ID:ttlbyte,项目名称:bokeh,代码行数:35,代码来源:script.py
示例11: new_module
def new_module(name, doc=None):
import sys
from types import ModuleType
m = ModuleType(name, doc)
m.__file__ = name + '.py'
sys.modules[name] = m
return m
开发者ID:RBINS,项目名称:mars,代码行数:7,代码来源:patches.py
示例12: __init__
def __init__(self, module, locals):
ModuleType.__init__(self, locals['__name__'])
self._imports = {}
ns = self.__dict__
ns.update(locals)
ns['__module__'] = self
lazy_symbols = {}
for symbol in module._get_symbol_names():
lazy_symbols[symbol] = ns[symbol] = _marker
ns.update(__dict__=LazyDict(self),
__bases__=(ModuleType,),
add_submodule=self.add_submodule)
def __getattribute__(_, name):
v = ns.get(name, _marker)
if v is not _marker:
return v
if name in lazy_symbols:
s = module._get_symbol(ns, name)
return s
elif name in self._imports:
m = __import__(self._imports[name], {}, {}, ' ')
ns[name] = m
return m
raise AttributeError(name)
LazyNamespace.__getattribute__ = __getattribute__
开发者ID:andrewbird,项目名称:vodafone-mobile-connect,代码行数:29,代码来源:_lazyutils.py
示例13: __new__
def __new__(meta, name, bases, dict):
mod = ModuleType(name, dict.get("__doc__"))
for key, obj in dict.items():
if isinstance(obj, FunctionType):
obj = meta.chained_function(meta, obj, mod)
mod.__dict__[key] = obj
return mod
开发者ID:felipecruz,项目名称:pyjulia,代码行数:7,代码来源:core.py
示例14: test_configure
def test_configure():
# a) keyword arguments
assert not hasattr(_Options, 'foo')
configure(foo='bar')
assert hasattr(_Options, 'foo')
del _Options.foo
# b) module
assert not hasattr(_Options, 'foo')
module = ModuleType('config')
module.MONGODB_FOO = 'bar'
module.NON_MONGO_ATTR = 'bar'
configure(foo='bar')
assert not hasattr(_Options, 'NON_MONGO_ATTR')
assert not hasattr(_Options, 'MONGODB_FOO')
assert hasattr(_Options, 'foo')
del _Options.foo
# c) non-module (fails silently)
try:
configure(42)
configure(None)
configure('foobar')
except Exception:
pytest.fail('configure() should fail silently on invalid input.')
开发者ID:Bloodevil,项目名称:minimongo,代码行数:25,代码来源:test_utils.py
示例15: test_update_artifact_metadata
def test_update_artifact_metadata(self):
# inject dummy module and add cleanup
mod = ModuleType('calmjs_testing_dummy')
mod.complete = generic_builder
self.addCleanup(sys.modules.pop, 'calmjs_testing_dummy')
sys.modules['calmjs_testing_dummy'] = mod
working_dir = utils.mkdtemp(self)
utils.make_dummy_dist(self, (
('requires.txt', '\n'.join([
'calmjs',
])),
('entry_points.txt', '\n'.join([
'[calmjs.artifacts]',
'artifact.js = calmjs_testing_dummy:complete',
])),
), 'app', '1.0', working_dir=working_dir)
# mock a version of calmjs within that environment too
utils.make_dummy_dist(self, (
('entry_points.txt', ''),
), 'calmjs', '1.0', working_dir=working_dir)
mock_ws = WorkingSet([working_dir])
registry = ArtifactRegistry('calmjs.artifacts', _working_set=mock_ws)
registry.update_artifact_metadata('app', {})
self.assertTrue(exists(registry.metadata.get('app')))
with pretty_logging(stream=mocks.StringIO()) as s:
registry.update_artifact_metadata('calmjs', {})
self.assertIn(
"package 'calmjs' has not declare any artifacts", s.getvalue())
开发者ID:calmjs,项目名称:calmjs,代码行数:31,代码来源:test_artifact.py
示例16: main
def main(module=None):
# Pygame won't run from a normal virtualenv copy of Python on a Mac
if not _check_python_ok_for_pygame():
_substitute_full_framework_python()
if not module:
parser = OptionParser()
options, args = parser.parse_args()
if len(args) != 1:
parser.error("You must specify which module to run.")
if __debug__:
warnings.simplefilter('default', DeprecationWarning)
path = args[0]
else:
path = module
with open(path) as f:
src = f.read()
code = compile(src, os.path.basename(path), 'exec', dont_inherit=True)
loaders.set_root(path)
pygame.display.set_mode((100, 100), DISPLAY_FLAGS)
name, _ = os.path.splitext(os.path.basename(path))
mod = ModuleType(name)
mod.__file__ = path
mod.__name__ = name
mod.__dict__.update(builtins.__dict__)
sys.modules[name] = mod
exec(code, mod.__dict__)
Juego(mod).run()
开发者ID:yrobla,项目名称:pyjuegos,代码行数:35,代码来源:runner.py
示例17: refresh_model
def refresh_model(self):
""" Refresh the compiled model object.
This method will (re)compile the model for the given model text
and update the 'compiled_model' attribute. If a compiled view is
available and has a member named 'model', the model will be
applied to the view.
"""
text = self.model_text
filename = self.model_filename
_fake_linecache(text, filename)
try:
if not text:
self.compiled_model = None
self._model_module = None
else:
code = compile(text, filename, 'exec')
module = ModuleType(filename.rsplit('.', 1)[0])
module.__file__ = filename
namespace = module.__dict__
exec_(code, namespace)
model = namespace.get(self.model_item, lambda: None)()
self.compiled_model = model
self._model_module = module
self.relink_view()
except Exception:
self.traceback = traceback.format_exc()
else:
self.traceback = ''
开发者ID:peterazmanov,项目名称:enaml,代码行数:30,代码来源:live_editor_model.py
示例18: update_from_file
def update_from_file(self, filename, overwrite=False):
"""Updates configuration from Python file.
For example, if there's :file:`dev.cfg`::
debug = False
database_uri = 'sqlite://'
so you can load it using :meth:`update_from_file()` method::
config.update_from_file('dev.cfg')
Like :meth:`update_from_object()` method, it also ignores
variables that start with underscore.
:param filename: the path of Python file to load
:type filename: :class:`basestring`
:param overwrite: keys that already exist are ignored by default.
if ``True`` has given to this parameter,
these are not overwritten
:type overwrite: :class:`bool`
"""
module = ModuleType(filename)
module.__file__ = abspath(filename)
execfile(filename, module.__dict__)
self.update_from_object(module, overwrite)
开发者ID:yoloseem,项目名称:plastic,代码行数:26,代码来源:config.py
示例19: test_minimum_sys_modules
def test_minimum_sys_modules():
# builtins stay
builtin_module = ModuleType('my_builtin')
modules = {'my_builtin': builtin_module}
new_modules = PEX.minimum_sys_modules([], modules)
assert new_modules == modules
new_modules = PEX.minimum_sys_modules(['bad_path'], modules)
assert new_modules == modules
# tainted evict
tainted_module = ModuleType('tainted_module')
tainted_module.__path__ = ['bad_path']
modules = {'tainted_module': tainted_module}
new_modules = PEX.minimum_sys_modules([], modules)
assert new_modules == modules
new_modules = PEX.minimum_sys_modules(['bad_path'], modules)
assert new_modules == {}
assert tainted_module.__path__ == []
# tainted cleaned
tainted_module = ModuleType('tainted_module')
tainted_module.__path__ = ['bad_path', 'good_path']
modules = {'tainted_module': tainted_module}
new_modules = PEX.minimum_sys_modules([], modules)
assert new_modules == modules
new_modules = PEX.minimum_sys_modules(['bad_path'], modules)
assert new_modules == modules
assert tainted_module.__path__ == ['good_path']
开发者ID:clam-gpsw,项目名称:pex,代码行数:28,代码来源:test_pex.py
示例20: create_module
def create_module(self, spec):
"""
Alter __path__ to equal spec.name (i.e qualname)
so we can catch consequent imports.
"""
m = ModuleType(spec.name)
m.__path__ = [m.__name__.lower()]
return m
开发者ID:DimitrisJim,项目名称:pipimporter,代码行数:8,代码来源:__init__.py
注:本文中的types.ModuleType类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论