本文整理汇总了Python中sys.displayhook方法的典型用法代码示例。如果您正苦于以下问题:Python sys.displayhook方法的具体用法?Python sys.displayhook怎么用?Python sys.displayhook使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sys
的用法示例。
在下文中一共展示了sys.displayhook方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: default
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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
示例2: system
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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()
示例3: system
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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)
示例4: dhook_wrap
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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
示例5: system_piped
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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))
示例6: displayhook
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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))
示例7: init_pprint
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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
示例8: test_pprint_compact
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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())
示例9: _reset_py_display
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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__
示例10: default
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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())
示例11: handle
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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)
示例12: begin
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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
示例13: displayhook
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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))
示例14: displayhook
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
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))
示例15: default
# 需要导入模块: import sys [as 别名]
# 或者: from sys import displayhook [as 别名]
def default(self, line):
"""Patched version to fix namespace with list comprehensions.
Fixes https://bugs.python.org/issue21161.
"""
self.history.append(line)
if line[:1] == '!':
line = line[1:]
locals = self.curframe_locals
ns = self.curframe.f_globals.copy()
ns.update(locals)
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, ns, 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())