我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.displayhook()。
def default(self, line): if line[:1] == '!': line = line[1:] locals = self.curframe_locals globals = self.curframe.f_globals try: code = compile(line + '\n', '<stdin>', 'single') save_stdout = sys.stdout save_stdin = sys.stdin save_displayhook = sys.displayhook try: sys.stdin = self.stdin sys.stdout = self.stdout sys.displayhook = self.displayhook exec code in globals, locals finally: sys.stdout = save_stdout sys.stdin = save_stdin sys.displayhook = save_displayhook except: t, v = sys.exc_info()[:2] if type(t) == type(''): exc_type_name = t else: exc_type_name = t.__name__ print >>self.stdout, '***', exc_type_name + ':', v
def displayhook(self, obj): self.locals['_'] = obj if isinstance(obj, defer.Deferred): # XXX Ick, where is my "hasFired()" interface? if hasattr(obj, "result"): self.write(repr(obj)) elif id(obj) in self._pendingDeferreds: self.write("<Deferred #%d>" % (self._pendingDeferreds[id(obj)][0],)) else: d = self._pendingDeferreds k = self.numDeferreds d[id(obj)] = (k, obj) self.numDeferreds += 1 obj.addCallbacks(self._cbDisplayDeferred, self._ebDisplayDeferred, callbackArgs=(k, obj), errbackArgs=(k, obj)) self.write("<Deferred #%d>" % (k,)) elif obj is not None: self.write(repr(obj))
def do_exec(self, arg, safe=True): if not self.frame: ret = RPCError("No current frame available to exec") else: locals = self.frame_locals globals = self.frame.f_globals code = compile(arg + '\n', '<stdin>', 'single') save_displayhook = sys.displayhook self.displayhook_value = None try: sys.displayhook = self.displayhook exec(code, globals, locals) ret = self.displayhook_value finally: sys.displayhook = save_displayhook if safe: ret = pydoc.cram(repr(ret), 255) return ret
def test_pprint_compact(self): with patch('sys.stdout', new_callable=StringIO) as mock_stdout: # - test compact pprint-ing with 80x25 terminal with patch.object(pythonrc.subprocess, 'check_output', return_value='25 80'): sys.displayhook(list(range(22))) self.assertIn('20, 21]', sys.stdout.getvalue()) sys.displayhook(list(range(23))) self.assertIn('21,\n 22]', sys.stdout.getvalue()) # - test compact pprint-ing with resized 100x25 terminal with patch.object(pythonrc.subprocess, 'check_output', return_value=('25 100')): sys.displayhook(list(range(23))) self.assertIn('21, 22]', sys.stdout.getvalue())
def init_pprint(self): """Activates pretty-printing of output values. """ keys_re = re.compile(r'([\'\("]+(.*?[\'\)"]: ))+?') color_dict = partial(keys_re.sub, lambda m: purple(m.group())) format_func = pprint.pformat if sys.version_info.major >= 3 and sys.version_info.minor > 3: format_func = partial(pprint.pformat, compact=True) def pprint_callback(value): if value is not None: try: rows, cols = os.get_teminal_size() except AttributeError: try: rows, cols = map(int, subprocess.check_output(['stty', 'size']).split()) except: cols = 80 builtins._ = value formatted = format_func(value, width=cols) print(color_dict(formatted) if issubclass(type(value), dict) else blue(formatted)) sys.displayhook = pprint_callback
def system(cmd): """Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str or list A command to be executed in the system shell. Returns ------- None : we explicitly do NOT return the subprocess status code, as this utility is meant to be used extensively in IPython, where any return value would trigger :func:`sys.displayhook` calls. """ # The controller provides interactivity with both # stdin and stdout #import _process_win32_controller #_process_win32_controller.system(cmd) with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) return process_handler(cmd, _system_body)
def system(cmd): """Win32 version of os.system() that works with network shares. Note that this implementation returns None, as meant for use in IPython. Parameters ---------- cmd : str A command to be executed in the system shell. Returns ------- None : we explicitly do NOT return the subprocess status code, as this utility is meant to be used extensively in IPython, where any return value would trigger :func:`sys.displayhook` calls. """ with AvoidUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) with Win32ShellCommandController(cmd) as scc: scc.run()
def _init_python_printing(stringify_func): """Setup printing in Python interactive session. """ import sys from sympy.core.compatibility import builtins def _displayhook(arg): """Python's pretty-printer display hook. This function was adapted from: http://www.python.org/dev/peps/pep-0217/ """ if arg is not None: builtins._ = None print(stringify_func(arg)) builtins._ = arg sys.displayhook = _displayhook
def default(self, line): if line[:1] == '!': line = line[1:] locals = self.curframe_locals globals = self.curframe.f_globals try: code = compile(line + '\n', '<stdin>', 'single') save_stdout = sys.stdout save_stdin = sys.stdin save_displayhook = sys.displayhook try: sys.stdin = self.stdin sys.stdout = self.stdout sys.displayhook = self.displayhook exec(code, globals, locals) finally: sys.stdout = save_stdout sys.stdin = save_stdin sys.displayhook = save_displayhook except: exc_info = sys.exc_info()[:2] self.error(traceback.format_exception_only(*exc_info)[-1].strip())
def begin(self): self.text.mark_set("iomark", "insert") self.resetoutput() if use_subprocess: nosub = '' client = self.interp.start_subprocess() if not client: self.close() return False else: nosub = ("==== No Subprocess ====\n\n" + "WARNING: Running IDLE without a Subprocess is deprecated\n" + "and will be removed in a later version. See Help/IDLE Help\n" + "for details.\n\n") sys.displayhook = rpc.displayhook self.write("Python %s on %s\n%s\n%s" % (sys.version, sys.platform, self.COPYRIGHT, nosub)) self.text.focus_force() self.showprompt() import tkinter tkinter._default_root = None # 03Jan04 KBK What's this? return True
def handle(self): """Override base method""" executive = Executive(self) self.register("exec", executive) self.console = self.get_remote_proxy("console") sys.stdin = PyShell.PseudoInputFile(self.console, "stdin", IOBinding.encoding) sys.stdout = PyShell.PseudoOutputFile(self.console, "stdout", IOBinding.encoding) sys.stderr = PyShell.PseudoOutputFile(self.console, "stderr", IOBinding.encoding) sys.displayhook = rpc.displayhook # page help() text to shell. import pydoc # import must be done here to capture i/o binding pydoc.pager = pydoc.plainpager # Keep a reference to stdin so that it won't try to exit IDLE if # sys.stdin gets changed from within IDLE's shell. See issue17838. self._keep_stdin = sys.stdin self.interp = self.get_remote_proxy("interp") rpc.RPCHandler.getresponse(self, myseq=None, wait=0.05)
def _init_python_printing(stringify_func, **settings): """Setup printing in Python interactive session. """ import sys from sympy.core.compatibility import builtins def _displayhook(arg): """Python's pretty-printer display hook. This function was adapted from: http://www.python.org/dev/peps/pep-0217/ """ if arg is not None: builtins._ = None print(stringify_func(arg, **settings)) builtins._ = arg sys.displayhook = _displayhook
def begin(self): self.text.mark_set("iomark", "insert") self.resetoutput() if use_subprocess: nosub = '' client = self.interp.start_subprocess() if not client: self.close() return False else: nosub = ("==== No Subprocess ====\n\n" + "WARNING: Running IDLE without a Subprocess is deprecated\n" + "and will be removed in a later version. See Help/IDLE Help\n" + "for details.\n\n") sys.displayhook = rpc.displayhook self.write("Python %s on %s\n%s\n%s" % (sys.version, sys.platform, self.COPYRIGHT, nosub)) self.showprompt() import tkinter tkinter._default_root = None # 03Jan04 KBK What's this? return True
def displayhook(self, obj): """Custom displayhook for the exec in default(), which prevents assignment of the _ variable in the builtins. """ # reproduce the behavior of the standard displayhook, not printing None if obj is not None: print repr(obj)
def displayhook(obj): try: stream = _local.stream except AttributeError: return _displayhook(obj) # stream._write bypasses escaping as debug_repr is # already generating HTML for us. if obj is not None: _local._current_ipy.locals['_'] = obj stream._write(debug_repr(obj))
def initialize_if_enabled(): backdoor_locals = { 'exit': _dont_use_this, # So we don't exit the entire process 'quit': _dont_use_this, # So we don't exit the entire process 'fo': _find_objects, 'pgt': _print_greenthreads, 'pnt': _print_nativethreads, } if CONF.backdoor_port is None: return None start_port, end_port = _parse_port_range(str(CONF.backdoor_port)) # NOTE(johannes): The standard sys.displayhook will print the value of # the last expression and set it to __builtin__._, which overwrites # the __builtin__._ that gettext sets. Let's switch to using pprint # since it won't interact poorly with gettext, and it's easier to # read the output too. def displayhook(val): if val is not None: pprint.pprint(val) sys.displayhook = displayhook sock = _listen('localhost', start_port, end_port, eventlet.listen) # In the case of backdoor port being zero, a port number is assigned by # listen(). In any case, pull the port number out here. port = sock.getsockname()[1] LOG.info( _LI('Eventlet backdoor listening on %(port)s for process %(pid)d') % {'port': port, 'pid': os.getpid()} ) eventlet.spawn_n(eventlet.backdoor.backdoor_server, sock, locals=backdoor_locals) return port
def runcode(self, *a, **kw): orighook, sys.displayhook = sys.displayhook, self.displayhook try: origout, sys.stdout = sys.stdout, FileWrapper(self.handler) try: code.InteractiveInterpreter.runcode(self, *a, **kw) finally: sys.stdout = origout finally: sys.displayhook = orighook
def setUp(self): if self._result_var is not None: self._old_displayhook = sys.displayhook sys.displayhook = self._displayhook super(DocTestCase, self).setUp()
def setUp(self): if self._result_var is not None: self._old_displayhook = sys.displayhook sys.displayhook = self._displayhook super(DocFileCase, self).setUp()
def tearDown(self): super(DocFileCase, self).tearDown() if self._result_var is not None: sys.displayhook = self._old_displayhook delattr(builtin_mod, self._result_var)
def run_locally_no_report(self, text, cur_frame, frame_kind): code = self.compile(text, cur_frame) res = eval(code, cur_frame.f_globals, self.get_locals(cur_frame, frame_kind)) self.locals_to_fast(cur_frame) sys.displayhook(res)