我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用__main__.__dict__()。
def run(self, cmd, globals=None, locals=None): if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() sys.settrace(self.trace_dispatch) if not isinstance(cmd, types.CodeType): cmd = cmd+'\n' try: exec cmd in globals, locals except BdbQuit: pass finally: self.quitting = 1 sys.settrace(None)
def runeval(self, expr, globals=None, locals=None): if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() sys.settrace(self.trace_dispatch) if not isinstance(expr, types.CodeType): expr = expr+'\n' try: return eval(expr, globals, locals) except BdbQuit: pass finally: self.quitting = 1 sys.settrace(None)
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_script(script_file): """Run the script at the provided path :param str script_file: A path to a python script to run """ builtins = __builtins__ import __main__ __main__.__dict__.clear() __main__.__dict__.update(dict( __name__ = "__main__", __file__ = script_file, __builtins__ = builtins )) globals = __main__.__dict__ locals = globals # repr will put the script_file into quotes and escape any # unruly characters # NOTE that at this point, sys.argv will already have been reset # so that it will look like (from script_file's point of view), # that it was the first file run instead of pipless. exec 'execfile({})'.format(repr(script_file)) in globals, locals
def _run_single_command(cmd): """Run a single command inside the virtual environment """ builtins = __builtins__ # this is how the python -c command works sys.argv.insert(0, "-c") import __main__ __main__.__dict__.clear() __main__.__dict__.update(dict( __name__ = "__main__", # file is not defined when 'python -c "print(__file__)"' is run #__file__ = script_file, __builtins__ = builtins )) globals = __main__.__dict__ locals = globals code = compile(cmd, "<string>", "single") exec code in globals, locals
def _run_interactive_shell(): """Run an interactive shell as if it were the first thing being run. """ builtins = __builtins__ code_ = code import __main__ __main__.__dict__.clear() __main__.__dict__.update(dict( __name__ = "__main__", # normal interactive shell leaves this undefined # __file__ = None, __builtins__ = builtins )) code_.interact()
def run(self, cmd, globals=None, locals=None): if globals is None: import __main__ globals = __main__.__dict__ if locals is None: locals = globals self.reset() if isinstance(cmd, str): cmd = compile(cmd, "<string>", "exec") sys.settrace(self.trace_dispatch) try: exec(cmd, globals, locals) except BdbQuit: pass finally: self.quitting = True sys.settrace(None)
def __init__(self, namespace = None): """Create a new completer for the command line. Completer([namespace]) -> completer instance. 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 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, builtins.__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 __gp_catch_functions(self, prefix): """ Internally used to catch functions with some specific prefix as non-terminals of the GP core """ import __main__ as mod_main function_set = {} main_dict = mod_main.__dict__ for obj, addr in main_dict.items(): if obj[0:len(prefix)] == prefix: try: op_len = addr.func_code.co_argcount except: continue function_set[obj] = op_len if len(function_set) <= 0: utils.raiseException("No function set found using function prefix '%s' !" % prefix, ValueError) self.setParams(gp_function_set=function_set) # -----------------------------------------------------------------
def _get_globals(): """Return current Python interpreter globals namespace""" if _get_globals_callback is not None: return _get_globals_callback() else: try: from __main__ import __dict__ as namespace except ImportError: try: # The import fails on IronPython import __main__ namespace = __main__.__dict__ except: namespace shell = namespace.get('__ipythonshell__') if shell is not None and hasattr(shell, 'user_ns'): # IPython 0.12+ kernel return shell.user_ns else: # Python interpreter return namespace return namespace
def OnViewBrowse( self, id, code ): " Called when ViewBrowse message is received " from pywin.mfc import dialog from pywin.tools import browser obName = dialog.GetSimpleInput('Object', '__builtins__', 'Browse Python Object') if obName is None: return try: browser.Browse(eval(obName, __main__.__dict__, __main__.__dict__)) except NameError: win32ui.MessageBox('This is no object with this name') except AttributeError: win32ui.MessageBox('The object has no attribute of that name') except: traceback.print_exc() win32ui.MessageBox('This object can not be browsed')
def Init(self): self.oldStdOut = self.oldStdErr = None # self.SetWordWrap(win32ui.CRichEditView_WrapNone) self.interp = PythonwinInteractiveInterpreter() self.OutputGrab() # Release at cleanup. if self.GetTextLength()==0: if self.banner is None: suffix = "" if win32ui.debug: suffix = ", debug build" sys.stderr.write("PythonWin %s on %s%s.\n" % (sys.version, sys.platform, suffix) ) sys.stderr.write("Portions %s - see 'Help/About PythonWin' for further copyright information.\n" % (win32ui.copyright,) ) else: sys.stderr.write(banner) rcfile = os.environ.get('PYTHONSTARTUP') if rcfile: import __main__ try: execfile(rcfile, __main__.__dict__, __main__.__dict__) except: sys.stderr.write(">>> \nError executing PYTHONSTARTUP script %r\n" % (rcfile)) traceback.print_exc(file=sys.stderr) self.AppendToPrompt([])
def RespondDebuggerState(self, state): globs = locs = None if state==DBGSTATE_BREAK: if self.debugger.curframe: globs = self.debugger.curframe.f_globals locs = self.debugger.curframe.f_locals elif state==DBGSTATE_NOT_DEBUGGING: import __main__ globs = locs = __main__.__dict__ for i in range(self.GetItemCount()-1): text = self.GetItemText(i, 0) if globs is None: val = "" else: try: val = repr( eval( text, globs, locs) ) except SyntaxError: val = "Syntax Error" except: t, v, tb = sys.exc_info() val = traceback.format_exception_only(t, v)[0].strip() tb = None # prevent a cycle. self.SetItemText(i, 1, val)
def get_object_at_cursor(self, wordchars="._" + string.ascii_uppercase + string.ascii_lowercase + string.digits): # XXX - This needs to be moved to a better place # so the "." attribute lookup code can also use it. text = self.text chars = text.get("insert linestart", "insert") i = len(chars) while i and chars[i-1] in wordchars: i = i-1 word = chars[i:] if word: # How is this for a hack! import sys, __main__ namespace = sys.modules.copy() namespace.update(__main__.__dict__) try: return eval(word, namespace) except: pass return None # Can't find an object.
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. """ matches = [] match_append = matches.append n = len(text) for lst in [keyword.kwlist, builtin_mod.__dict__.keys(), self.namespace.keys(), self.global_namespace.keys()]: for word in lst: if word[:n] == text and word != "__builtins__": match_append(word) return [cast_unicode_py2(m) for m in matches]
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 not text.strip(): if state == 0: return '\t' else: return None 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 [builtins.__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