我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用__builtin__.__dict__()。
def CreateApplication(self): if os.path.exists("BEREMIZ_DEBUG"): __builtin__.__dict__["BMZ_DBG"] = True else: __builtin__.__dict__["BMZ_DBG"] = False global wx import wx if wx.VERSION >= (3, 0, 0): self.app = wx.App(redirect=BMZ_DBG) else: self.app = wx.PySimpleApp(redirect=BMZ_DBG) self.app.SetAppName('beremiz') if wx.VERSION < (3, 0, 0): wx.InitAllImageHandlers() self.ShowSplashScreen() self.BackgroundInitialization() self.app.MainLoop()
def complete(self, text, state): """Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. """ if self.use_main_ns: self.namespace = __main__.__dict__ if state == 0: if "." in text: self.matches = self.attr_matches(text) else: self.matches = self.global_matches(text) try: return self.matches[state] except IndexError: return None
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. """ import keyword matches = [] n = len(text) for word in keyword.kwlist: if word[:n] == text: matches.append(word) for nspace in [__builtin__.__dict__, self.namespace]: for word, val in nspace.items(): if word[:n] == text and word != "__builtins__": matches.append(self._callable_postfix(val, word)) return matches
def _run(self): try: try: console = InteractiveConsole(self.locals) # __builtins__ may either be the __builtin__ module or # __builtin__.__dict__ in the latter case typing # locals() at the backdoor prompt spews out lots of # useless stuff import __builtin__ console.locals["__builtins__"] = __builtin__ console.interact(banner=self.banner) except SystemExit: # raised by quit() sys.exc_clear() finally: self.switch_out() self.finalize()
def _create_interactive_locals(self): # Create and return a *new* locals dictionary based on self.locals, # and set any new entries in it. (InteractiveConsole does not # copy its locals value) _locals = self.locals.copy() # __builtins__ may either be the __builtin__ module or # __builtin__.__dict__; in the latter case typing # locals() at the backdoor prompt spews out lots of # useless stuff try: import __builtin__ _locals["__builtins__"] = __builtin__ except ImportError: import builtins _locals["builtins"] = builtins _locals['__builtins__'] = builtins return _locals
def _create_interactive_locals(self): # Create and return a *new* locals dictionary based on self.locals, # and set any new entries in it. (InteractiveConsole does not # copy its locals value) _locals = self.locals.copy() # __builtins__ may either be the __builtin__ module or # __builtin__.__dict__; in the latter case typing # locals() at the backdoor prompt spews out lots of # useless stuff try: import __builtin__ _locals["__builtins__"] = __builtin__ except ImportError: import builtins # pylint:disable=import-error _locals["builtins"] = builtins _locals['__builtins__'] = builtins return _locals
def _find_non_builtin_globals(source, codeobj): try: import ast except ImportError: return None try: import __builtin__ except ImportError: import builtins as __builtin__ vars = dict.fromkeys(codeobj.co_varnames) return [ node.id for node in ast.walk(ast.parse(source)) if isinstance(node, ast.Name) and node.id not in vars and node.id not in __builtin__.__dict__ ]
def __init__(self, head = HEAD_WORD_LSB): self.sock = None # socket object self.send_buf = '' # send buffer self.recv_buf = '' # recv buffer self.state = NET_STATE_STOP self.errd = [ errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK ] self.conn = ( errno.EISCONN, 10057, 10053 ) self.errc = 0 self.headmsk = False self.headraw = False self.__head_init(head) self.crypts = None self.cryptr = None self.ipv6 = False self.eintr = () if 'EINTR' in errno.__dict__: self.eintr = (errno.__dict__['EINTR'],) if 'WSAEWOULDBLOCK' in errno.__dict__: self.errd.append(errno.WSAEWOULDBLOCK) self.errd = tuple(self.errd) self.block = False
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. """ import keyword matches = [] seen = {"__builtins__"} n = len(text) for word in keyword.kwlist: if word[:n] == text: seen.add(word) matches.append(word) for nspace in [self.namespace, __builtin__.__dict__]: for word, val in nspace.items(): if word[:n] == text and word not in seen: seen.add(word) matches.append(self._callable_postfix(val, word)) return matches
def __init__(self, namespace): """Create a new completer for the command line. Completer([namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be given as dictionaries. Completer instances should be used as the completion mechanism of readline via the set_completer() call: readline.set_completer(Completer(my_namespace).complete) """ if namespace and not isinstance(namespace, dict): raise TypeError,'namespace must be a dictionary' self.namespace = namespace
def replace_builtin_property(new_property=None): if new_property is None: new_property = DebugProperty original = property if not IS_PY3K: try: import __builtin__ __builtin__.__dict__['property'] = new_property except: if DebugInfoHolder.DEBUG_TRACE_LEVEL: import traceback;traceback.print_exc() #@Reimport else: try: import builtins #Python 3.0 does not have the __builtin__ module @UnresolvedImport builtins.__dict__['property'] = new_property except: if DebugInfoHolder.DEBUG_TRACE_LEVEL: import traceback;traceback.print_exc() #@Reimport return original #======================================================================================================================= # DebugProperty #=======================================================================================================================
def complete(self, text): """Return the next possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. """ if self.use_main_ns: #In pydev this option should never be used raise RuntimeError('Namespace must be provided!') self.namespace = __main__.__dict__ #@UndefinedVariable if "." in text: return self.attr_matches(text) else: return self.global_matches(text)
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match. """ def get_item(obj, attr): return obj[attr] a = {} for dict_with_comps in [__builtin__.__dict__, self.namespace, self.global_namespace]: #@UndefinedVariable a.update(dict_with_comps) filter = _StartsWithFilter(text) return dir2(a, a.keys(), get_item, filter)
def __init__(self, items, start=0): if type(items) == types.StringType: items = items.split(',') self._stringTable = {} # make sure we don't overwrite an existing element of the class assert self._checkExistingMembers(items) assert uniqueElements(items) i = start for item in items: # remove leading/trailing whitespace item = string.strip(item) # is there anything left? if len(item) == 0: continue # make sure there are no invalid characters assert Enum._checkValidIdentifier(item) self.__dict__[item] = i self._stringTable[i] = item i += 1
def _find_function_module(func): """ @return: The module that defines the given function. @rtype: C{module} @param func: The function whose module should be found. @type func: C{function} """ if hasattr(func, '__module__'): return func.__module__ try: module = inspect.getmodule(func) if module: return module.__name__ except KeyboardInterrupt: raise except: pass # This fallback shouldn't usually be needed. But it is needed in # a couple special cases (including using epydoc to document # itself). In particular, if a module gets loaded twice, using # two different names for the same file, then this helps. for module in sys.modules.values(): if (hasattr(module, '__dict__') and hasattr(func, 'func_globals') and func.func_globals is module.__dict__): return module.__name__ return None #//////////////////////////////////////////////////////////// # Introspection Dispatch Table #////////////////////////////////////////////////////////////
def get_value_from_name(name, globs=None): """ Given a name, return the corresponding value. @param globs: A namespace to check for the value, if there is no module containing the named value. Defaults to __builtin__. """ name = DottedName(name) # Import the topmost module/package. If we fail, then check if # the requested name refers to a builtin. try: module = _import(name[0]) except ImportError, e: if globs is None: globs = __builtin__.__dict__ if name[0] in globs: try: return _lookup(globs[name[0]], name[1:]) except: raise e else: raise # Find the requested value in the module/package or its submodules. for i in range(1, len(name)): try: return _lookup(module, name[i:]) except ImportError: pass module = _import('.'.join(name[:i+1])) module = _lookup(module, name[1:i+1]) return module
def install(self, unicode=False, names=None): import __builtin__ __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext if hasattr(names, "__contains__"): if "gettext" in names: __builtin__.__dict__['gettext'] = __builtin__.__dict__['_'] if "ngettext" in names: __builtin__.__dict__['ngettext'] = (unicode and self.ungettext or self.ngettext) if "lgettext" in names: __builtin__.__dict__['lgettext'] = self.lgettext if "lngettext" in names: __builtin__.__dict__['lngettext'] = self.lngettext
def __init__(self, namespace = None): """Create a new completer for the command line. Completer([namespace]) -> completer instance. If unspecified, the default namespace where completions are performed is __main__ (technically, __main__.__dict__). Namespaces should be given as dictionaries. Completer instances should be used as the completion mechanism of readline via the set_completer() call: readline.set_completer(Completer(my_namespace).complete) """ if namespace and not isinstance(namespace, dict): raise TypeError,'namespace must be a dictionary' # Don't bind to namespace quite yet, but flag whether the user wants a # specific namespace or to use __main__.__dict__. This will allow us # to bind to __main__.__dict__ at completion time, not now. if namespace is None: self.use_main_ns = 1 else: self.use_main_ns = 0 self.namespace = namespace
def _load(module): try: mod = __import__(module,globals(),locals(),".") __builtin__.__dict__.update(mod.__dict__) except Exception,e: log_interactive.error(e)
def save_session(fname=None, session=None, pickleProto=-1): if fname is None: fname = conf.session if not fname: conf.session = fname = utils.get_temp_file(keep=True) log_interactive.info("Use [%s] as session file" % fname) if session is None: session = __builtin__.__dict__["scapy_session"] to_be_saved = session.copy() if to_be_saved.has_key("__builtins__"): del(to_be_saved["__builtins__"]) for k in to_be_saved.keys(): if type(to_be_saved[k]) in [types.TypeType, types.ClassType, types.ModuleType]: log_interactive.error("[%s] (%s) can't be saved." % (k, type(to_be_saved[k]))) del(to_be_saved[k]) try: os.rename(fname, fname+".bak") except OSError: pass f=gzip.open(fname,"wb") cPickle.dump(to_be_saved, f, pickleProto) f.close()
def load_session(fname=None): if fname is None: fname = conf.session try: s = cPickle.load(gzip.open(fname,"rb")) except IOError: s = cPickle.load(open(fname,"rb")) scapy_session = __builtin__.__dict__["scapy_session"] scapy_session.clear() scapy_session.update(s)
def update_session(fname=None): if fname is None: fname = conf.session try: s = cPickle.load(gzip.open(fname,"rb")) except IOError: s = cPickle.load(open(fname,"rb")) scapy_session = __builtin__.__dict__["scapy_session"] scapy_session.update(s) ################ ##### Main ##### ################
def autorun_commands(cmds,my_globals=None,verb=0): sv = conf.verb import __builtin__ try: try: if my_globals is None: my_globals = __import__("scapy.all").all.__dict__ conf.verb = verb interp = ScapyAutorunInterpreter(my_globals) cmd = "" cmds = cmds.splitlines() cmds.append("") # ensure we finish multiline commands cmds.reverse() __builtin__.__dict__["_"] = None while 1: if cmd: sys.stderr.write(sys.__dict__.get("ps2","... ")) else: sys.stderr.write(str(sys.__dict__.get("ps1",ColorPrompt()))) l = cmds.pop() print l cmd += "\n"+l if interp.runsource(cmd): continue if interp.error: return 0 cmd = "" if len(cmds) <= 1: break except SystemExit: pass finally: conf.verb = sv return _
def instance(klass, d): if isinstance(klass, types.ClassType): return new.instance(klass, d) elif isinstance(klass, type): o = object.__new__(klass) o.__dict__ = d return o else: raise TypeError, "%s is not a class" % klass
def jellyToDOM(self, jellier, element): element.setAttribute("marmalade:version", str(self.jellyDOMVersion)) method = getattr(self, "jellyToDOM_%s" % self.jellyDOMVersion, None) if method: method(jellier, element) else: element.appendChild(jellier.jellyToNode(self.__dict__))
def unjellyFromDOM(self, unjellier, element): pDOMVersion = element.getAttribute("marmalade:version") or "0" method = getattr(self, "unjellyFromDOM_%s" % pDOMVersion, None) if method: method(unjellier, element) else: # XXX: DOMJellyable.unjellyNode does not exist # XXX: 'node' is undefined - did you mean 'self', 'element', or 'Node'? state = self.unjellyNode(getValueElement(node)) if hasattr(self.__class__, "__setstate__"): self.__setstate__(state) else: self.__dict__ = state
def unjellyAttribute(self, instance, attrName, valueNode): """Utility method for unjellying into instances of attributes. Use this rather than unjellyNode unless you like surprising bugs! Alternatively, you can use unjellyInto on your instance's __dict__. """ self.unjellyInto(instance.__dict__, attrName, valueNode)