Python sys.displayhook() Examples
The following are 30
code examples of sys.displayhook().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sys
, or try the search function
.
Example #1
Source File: pdb.py From ironpython3 with Apache License 2.0 | 6 votes |
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())
Example #2
Source File: pdb.py From ironpython2 with Apache License 2.0 | 6 votes |
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
Example #3
Source File: pdb.py From meddle with MIT License | 6 votes |
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
Example #4
Source File: pdb.py From BinderFilter with MIT License | 6 votes |
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
Example #5
Source File: _process_win32_controller.py From Computable with MIT License | 6 votes |
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()
Example #6
Source File: _process_win32.py From Computable with MIT License | 6 votes |
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. """ # 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)
Example #7
Source File: doctestreload.py From Computable with MIT License | 6 votes |
def dhook_wrap(func,*a,**k): """Wrap a function call in a sys.displayhook controller. Returns a wrapper around func which calls func, with all its arguments and keywords unmodified, using the default sys.displayhook. Since IPython modifies sys.displayhook, it breaks the behavior of certain systems that rely on the default behavior, notably doctest. """ def f(*a,**k): dhook_s = sys.displayhook sys.displayhook = sys.__displayhook__ try: out = func(*a,**k) finally: sys.displayhook = dhook_s return out f.__doc__ = func.__doc__ return f
Example #8
Source File: interactiveshell.py From Computable with MIT License | 6 votes |
def system_piped(self, cmd): """Call the given cmd in a subprocess, piping stdout/err Parameters ---------- cmd : str Command to execute (can not end in '&', as background processes are not supported. Should not be a command that expects input other than simple text. """ if cmd.rstrip().endswith('&'): # this is *far* from a rigorous test # We do not support backgrounding processes because we either use # pexpect or pipes to read from. Users can always just call # os.system() or use ip.system=ip.system_raw # if they really want a background process. raise OSError("Background processes not supported.") # we explicitly do NOT return the subprocess status code, because # a non-None value would trigger :func:`sys.displayhook` calls. # Instead, we store the exit_code in user_ns. self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
Example #9
Source File: pdb.py From oss-ftp with MIT License | 6 votes |
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
Example #10
Source File: manhole.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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))
Example #11
Source File: test_pythonrc.py From pythonrc with MIT License | 6 votes |
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())
Example #12
Source File: cmd2.py From WebPocket with GNU General Public License v3.0 | 6 votes |
def _reset_py_display() -> None: """ Resets the dynamic objects in the sys module that the py and ipy consoles fight over. When a Python console starts it adopts certain display settings if they've already been set. If an ipy console has previously been run, then py uses its settings and ends up looking like an ipy console in terms of prompt and exception text. This method forces the Python console to create its own display settings since they won't exist. IPython does not have this problem since it always overwrites the display settings when it is run. Therefore this method only needs to be called before creating a Python console. """ # Delete any prompts that have been set attributes = ['ps1', 'ps2', 'ps3'] for cur_attr in attributes: try: del sys.__dict__[cur_attr] except KeyError: pass # Reset functions sys.displayhook = sys.__displayhook__ sys.excepthook = sys.__excepthook__
Example #13
Source File: pdb.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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())
Example #14
Source File: run.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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)
Example #15
Source File: PyShell.py From Fluid-Designer with GNU General Public License v3.0 | 6 votes |
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
Example #16
Source File: pdb.py From Imogen with MIT License | 6 votes |
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())
Example #17
Source File: pythonrc.py From pythonrc with MIT License | 6 votes |
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 formatted = format_func(value, width=cols) print(color_dict(formatted) if issubclass(type(value), dict) else blue(formatted)) self.locals['_'] = value sys.displayhook = pprint_callback
Example #18
Source File: manhole.py From learn_python3_spider with MIT License | 6 votes |
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))
Example #19
Source File: pdb.py From Computable with MIT License | 6 votes |
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
Example #20
Source File: manhole.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
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
Example #21
Source File: test_pythonrc.py From pythonrc with MIT License | 5 votes |
def test_init_pprint(self): self.assertEqual(sys.displayhook.__name__, 'pprint_callback') with patch('sys.stdout', new_callable=StringIO) as mock_stdout: sys.displayhook(42) sys.displayhook({'spam': 42}) self.assertEqual( sys.stdout.getvalue(), ("%s\n" "{%s42}\n") % (pythonrc.blue('42'), pythonrc.purple("'spam': ")) )
Example #22
Source File: test_sys.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_lost_displayhook(self): olddisplayhook = sys.displayhook del sys.displayhook code = compile("42", "<string>", "single") self.assertRaises(RuntimeError, eval, code) sys.displayhook = olddisplayhook
Example #23
Source File: test_sys.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_custom_displayhook(self): olddisplayhook = sys.displayhook def baddisplayhook(obj): raise ValueError sys.displayhook = baddisplayhook code = compile("42", "<string>", "single") self.assertRaises(ValueError, eval, code) sys.displayhook = olddisplayhook
Example #24
Source File: pyplot.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def uninstall_repl_displayhook(): """ Uninstall the matplotlib display hook. .. warning Need IPython >= 2 for this to work. For IPython < 2 will raise a ``NotImplementedError`` .. warning If you are using vanilla python and have installed another display hook this will reset ``sys.displayhook`` to what ever function was there when matplotlib installed it's displayhook, possibly discarding your changes. """ global _IP_REGISTERED global _INSTALL_FIG_OBSERVER if _IP_REGISTERED: from IPython import get_ipython ip = get_ipython() try: ip.events.unregister('post_execute', _IP_REGISTERED) except AttributeError: raise NotImplementedError("Can not unregister events " "in IPython < 2.0") _IP_REGISTERED = None if _INSTALL_FIG_OBSERVER: _INSTALL_FIG_OBSERVER = False
Example #25
Source File: pyplot.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def uninstall_repl_displayhook(): """ Uninstall the matplotlib display hook. .. warning Need IPython >= 2 for this to work. For IPython < 2 will raise a ``NotImplementedError`` .. warning If you are using vanilla python and have installed another display hook this will reset ``sys.displayhook`` to what ever function was there when matplotlib installed it's displayhook, possibly discarding your changes. """ global _IP_REGISTERED global _INSTALL_FIG_OBSERVER if _IP_REGISTERED: from IPython import get_ipython ip = get_ipython() try: ip.events.unregister('post_execute', _IP_REGISTERED) except AttributeError: raise NotImplementedError("Can not unregister events " "in IPython < 2.0") _IP_REGISTERED = None if _INSTALL_FIG_OBSERVER: _INSTALL_FIG_OBSERVER = False
Example #26
Source File: pdb.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
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: self.message(repr(obj))
Example #27
Source File: pdb.py From ironpython2 with Apache License 2.0 | 5 votes |
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)
Example #28
Source File: test_doctest.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def displayhook(): r""" Test that changing sys.displayhook doesn't matter for doctest. >>> import sys >>> orig_displayhook = sys.displayhook >>> def my_displayhook(x): ... print('hi!') >>> sys.displayhook = my_displayhook >>> def f(): ... ''' ... >>> 3 ... 3 ... ''' >>> test = doctest.DocTestFinder().find(f)[0] >>> r = doctest.DocTestRunner(verbose=False).run(test) >>> post_displayhook = sys.displayhook We need to restore sys.displayhook now, so that we'll be able to test results. >>> sys.displayhook = orig_displayhook Ok, now we can check that everything is ok. >>> r TestResults(failed=0, attempted=1) >>> post_displayhook is my_displayhook True """
Example #29
Source File: console.py From lambda-packs with MIT License | 5 votes |
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))
Example #30
Source File: test_sys.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def tearDown(self): sys.stdout = self.orig_stdout sys.stderr = self.orig_stderr sys.displayhook = self.orig_displayhook test.support.reap_children()