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
python类__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()
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 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 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 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 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 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
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