我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.builtin_module_names()。
def find_module(self, name, path, parent=None): if parent is not None: # assert path is not None fullname = parent.__name__+'.'+name else: fullname = name if fullname in self.excludes: self.msgout(3, "find_module -> Excluded", fullname) raise ImportError, name if path is None: if name in sys.builtin_module_names: return (None, None, ("", "", imp.C_BUILTIN)) path = self.path return imp.find_module(name, path)
def _locate_engine_class(ffi, force_generic_engine): if _FORCE_GENERIC_ENGINE: force_generic_engine = True if not force_generic_engine: if '__pypy__' in sys.builtin_module_names: force_generic_engine = True else: try: import _cffi_backend except ImportError: _cffi_backend = '?' if ffi._backend is not _cffi_backend: force_generic_engine = True if force_generic_engine: from . import vengine_gen return vengine_gen.VGenericEngine else: from . import vengine_cpy return vengine_cpy.VCPythonEngine # ____________________________________________________________
def search(func, depth=1): local_vars = sys._getframe(depth).f_locals source = get_source_code(func) tree = ast.parse(source) child_funcs = [] for node in ast.walk(tree): if isinstance(node, ast.Call): if isinstance(node.func, ast.Name): child_funcs.append(node.func.id) elif (isinstance(node, ast.Name) and node.id in local_vars and callable(local_vars[node.id]) and node.id not in sys.builtin_module_names): child_funcs.append(node.id) child_load_str = '' for child in child_funcs: if child in local_vars: try: load_string = search(local_vars[child], depth=(depth + 1)) child_load_str += load_string + '\n' except Exception as e: pass load_str = child_load_str + source return load_str
def _get_module_names(self, search_path=None): """ Get the names of all modules in the search_path. This means file names and not names defined in the files. """ names = [] # add builtin module names if search_path is None: names += [self._generate_name(name) for name in sys.builtin_module_names] if search_path is None: search_path = self.sys_path_with_modifications() for module_loader, name, is_pkg in pkgutil.iter_modules(search_path): names.append(self._generate_name(name)) return names
def _run(self, options=None): """ Run iostat command. """ close_fds = 'posix' in sys.builtin_module_names args = '%s %s %s %s %s' % ( self.path, ''.join(options), self.interval, self.count, ' '.join(self.disks)) return subprocess.Popen( args, bufsize=1, shell=True, stdout=subprocess.PIPE, close_fds=close_fds)
def _get_module_names(self, search_path=None, in_module=None): """ Get the names of all modules in the search_path. This means file names and not names defined in the files. """ names = [] # add builtin module names if search_path is None and in_module is None: names += [self._generate_name(name) for name in sys.builtin_module_names] if search_path is None: search_path = self.sys_path_with_modifications() for module_loader, name, is_pkg in pkgutil.iter_modules(search_path): names.append(self._generate_name(name, in_module=in_module)) return names
def find_module(self, name, path, parent=None): if parent is not None: # assert path is not None fullname = parent.__name__+'.'+name else: fullname = name if fullname in self.excludes: self.msgout(3, "find_module -> Excluded", fullname) raise ImportError(name) if path is None: if name in sys.builtin_module_names: return (None, None, ("", "", imp.C_BUILTIN)) path = self.path return imp.find_module(name, path)
def call_pydevd(): """ trap into the pydevd debugger""" import os,sys pydevdir= '/home/mah/.eclipse/org.eclipse.platform_3.5.0_155965261/plugins/org.python.pydev.debug_2.0.0.2011040403/pysrc/' # the 'emctask' module is present only in the milltask instance, otherwise both the UI and # milltask would try to connect to the debug server. if os.path.isdir(pydevdir) and 'emctask' in sys.builtin_module_names: sys.path.append(pydevdir) sys.path.insert(0,pydevdir) try: import pydevd emccanon.MESSAGE("pydevd imported, connecting to Eclipse debug server...") pydevd.settrace() except: emccanon.MESSAGE("no pydevd module found") pass
def reloadModules(pattern='.*', skipPattern='^IPython'): ''' Reload modules that match pattern regular expression (string or compile re) ''' from types import ModuleType import sys import os import re pattern = re.compile(pattern) skipPattern = re.compile(skipPattern) modules = sys.modules.keys() #In case something is loaded in the background, it will craete a #"dictionary changed size during iteration" error for m in modules: if isinstance(sys.modules[m], ModuleType) and \ m not in sys.builtin_module_names and \ '(built-in)' not in str(sys.modules[m]) and \ pattern.search(m) and \ not skipPattern.search(m): with Try(): reload(sys.modules[m])
def test_run_with_builtin_module(self): """If a built-in module is passed as a handler to run, an exception should be raised To get the list of all modules that are compiled into this Python interpreter, do: print sys.builtin_module_names sys happens to be one of these modules """ handler = 'sys.exit' expected = { 'exc_message': ( 'Built-in module "sys" cannot be a handler module' ), 'exc_type': 'Exception', 'stack_trace': '', } result = self.runner.run(event={}, context=None, handler=handler) actual = json.loads(result) self.assertEqual(None, actual['value']) self.assertDictEqual(expected, actual['error'])
def timeit(self, number=default_number): """Time 'number' executions of the main statement. To be precise, this executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, as a float measured in seconds. The argument is the number of times through the loop, defaulting to one million. The main statement, the setup statement and the timer function to be used are passed to the constructor. """ inner = self.make_inner() gcold = gc.isenabled() if '__pypy__' not in sys.builtin_module_names: gc.disable() # only do that on CPython try: timing = inner(number, self.timer) finally: if gcold: gc.enable() return timing
def copy_required_modules(dst_prefix): import imp for modname in REQUIRED_MODULES: if modname in sys.builtin_module_names: logger.info("Ignoring built-in bootstrap module: %s" % modname) continue try: f, filename, _ = imp.find_module(modname) except ImportError: logger.info("Cannot import bootstrap module: %s" % modname) else: if f is not None: f.close() dst_filename = change_prefix(filename, dst_prefix) copyfile(filename, dst_filename) if filename.endswith('.pyc'): pyfile = filename[:-1] if os.path.exists(pyfile): copyfile(pyfile, dst_filename[:-1])
def find_path(name): # Reject invalid module names if not is_valid_name(name): raise ValueError(name + " is not a valid module name") name = str(name).strip() # Check if built-in if name in sys.builtin_module_names: return "<built-in>" # Check all sys.path locations for p in sys.path: loc = os.path.abspath(os.path.join(p, name + ".py")) if os.path.exists(loc) and os.path.isfile(loc): return loc # Last resort, import module and check __file__ try: mod = __import__(name) except ImportError: # Everything failed, assume nonexistant return "<string>" return mod.__file__ if hasattr(mod, "__file__") else "<built-in>"
def _get_module_names(self, search_path=None): """ Get the names of all modules in the search_path. This means file names and not names defined in the files. """ names = [] # add builtin module names if search_path is None: names += [self._generate_name(name) for name in sys.builtin_module_names] if search_path is None: search_path = self._importer.sys_path_with_modifications() for module_loader, name, is_pkg in pkgutil.iter_modules(search_path): names.append(self._generate_name(name)) return names
def __init__(self, includeFiles = None, excludes = [], path = None, replacePaths = None): self.includeFiles = includeFiles if includeFiles is None: self.includeFiles = [] self.excludeDependentFiles = {} self.excludes = dict.fromkeys(excludes) self.replacePaths = replacePaths if replacePaths is None: self.replacePaths = [] self.path = path or sys.path self.modules = [] self.aliases = {} self._modules = dict.fromkeys(excludes) self._builtinModules = dict.fromkeys(sys.builtin_module_names) self._badModules = {} self._zip_modules_cache = ZipModulesCache() cx_Freeze.hooks.initialize(self) initialExcludedModules = self.excludes.copy() self._AddBaseModules()
def make_sys(self): m = self.copy_only(sys, self.ok_sys_names) m.modules = self.modules m.argv = ['RESTRICTED'] m.path = map(None, self.ok_path) m.exc_info = self.r_exc_info m = self.modules['sys'] l = self.modules.keys() + list(self.ok_builtin_modules) l.sort() m.builtin_module_names = tuple(l) # The copy_* methods copy existing modules with some changes
def _os_bootstrap(): "Set up 'os' module replacement functions for use during import bootstrap." names = sys.builtin_module_names join = None if 'posix' in names: sep = '/' from posix import stat elif 'nt' in names: sep = '\\' from nt import stat elif 'dos' in names: sep = '\\' from dos import stat elif 'os2' in names: sep = '\\' from os2 import stat else: raise ImportError, 'no os specific module found' if join is None: def join(a, b, sep=sep): if a == '': return b lastchar = a[-1:] if lastchar == '/' or lastchar == sep: return a + b return a + sep + b global _os_stat _os_stat = stat global _os_path_join _os_path_join = join
def run(self, callback, key=None, completer=None, onerror=None): if key: key = lower(key) self.quit = False seen = {} for modname in sys.builtin_module_names: if modname != '__main__': seen[modname] = 1 if key is None: callback(None, modname, '') else: desc = split(__import__(modname).__doc__ or '', '\n')[0] if find(lower(modname + ' - ' + desc), key) >= 0: callback(None, modname, desc) for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror): if self.quit: break if key is None: callback(None, modname, '') else: loader = importer.find_module(modname) if hasattr(loader,'get_source'): import StringIO desc = source_synopsis( StringIO.StringIO(loader.get_source(modname)) ) or '' if hasattr(loader,'get_filename'): path = loader.get_filename(modname) else: path = None else: module = loader.load_module(modname) desc = (module.__doc__ or '').splitlines()[0] path = getattr(module,'__file__',None) if find(lower(modname + ' - ' + desc), key) >= 0: callback(path, modname, desc) if completer: completer()