本文整理汇总了Python中sys.displayhook函数的典型用法代码示例。如果您正苦于以下问题:Python displayhook函数的具体用法?Python displayhook怎么用?Python displayhook使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了displayhook函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: edit_syntax_error
def edit_syntax_error(self):
"""The bottom half of the syntax error handler called in the main loop.
Loop until syntax error is fixed or user cancels.
"""
while self.SyntaxTB.last_syntax_error:
# copy and clear last_syntax_error
err = self.SyntaxTB.clear_err_state()
if not self._should_recompile(err):
return
try:
# may set last_syntax_error again if a SyntaxError is raised
self.safe_execfile(err.filename,self.user_ns)
except:
self.showtraceback()
else:
try:
f = open(err.filename)
try:
# This should be inside a display_trap block and I
# think it is.
sys.displayhook(f.read())
finally:
f.close()
except:
self.showtraceback()
示例2: pre_prompt
def pre_prompt(self, ip):
ec = self.shell.execution_count
try:
for num, result in self.delayed:
self.shell.execution_count = num
sys.displayhook(result)
self.delayed = []
finally:
self.shell.execution_count = ec
示例3: pretty_print
def pretty_print(thing):
if isinstance(thing, str):
py_print(thing)
elif not isinstance(thing, (Mapping, Sequence)) and isinstance(thing, Iterable):
sliced = []
for n, item in enumerate(thing):
if n < 5:
sliced.append(item)
else:
sliced.append(raw('...'))
break
py_print("<iterable {}>".format(repr(sliced)))
else:
sys.displayhook(thing)
示例4: pretty_print
def pretty_print(thing):
if isinstance(thing, str):
_write(thing)
_write('\n')
elif not isinstance(thing, (Mapping, Sequence)) and isinstance(thing, Iterable):
sliced = []
for n, item in enumerate(thing):
if n < 5:
sliced.append(repr(item))
else:
sliced.append('...')
break
py_print("<iterable [{}]>".format(', '.join(sliced)))
else:
sys.displayhook(thing)
return thing
示例5: showcmd
def showcmd(args, stdin=None):
"""usage: showcmd [-h|--help|cmd args]
Displays the command and arguments as a list of strings that xonsh would
run in subprocess mode. This is useful for determining how xonsh evaluates
your commands and arguments prior to running these commands.
optional arguments:
-h, --help show this help message and exit
example:
>>> showcmd echo $USER can't hear "the sea"
['echo', 'I', "can't", 'hear', 'the sea']
"""
if len(args) == 0 or (len(args) == 1 and args[0] in {'-h', '--help'}):
print(showcmd.__doc__.rstrip().replace('\n ', '\n'))
else:
sys.displayhook(args)
示例6: shell_substitute_run_ast_nodes
def shell_substitute_run_ast_nodes(
self,
nodelist, cellname, interactivity='last_expr',
compiler=compile, # ignored
result=None,
):
"""
Replaces get_ipython().run_ast_nodes
"""
if not nodelist:
return
try:
result_val = self.exec_ast_nodes(nodelist)
if interactivity == 'last_expr':
sys.displayhook(result_val)
return False
except:
if result:
result.error_before_exec = sys.exc_info()[1]
self.shell.showtraceback()
return True
示例7: evaluate
def evaluate(self, statement, session, printer=None, stream=None):
"""Evaluate the statement in sessions's globals. """
# the Python compiler doesn't like network line endings
source = statement.replace('\r\n', '\n').rstrip()
# split source code into 'exec' and 'eval' parts
exec_source, eval_source = self.split(source)
try:
self.compile(eval_source, 'eval')
except (OverflowError, SyntaxError, ValueError):
exec_source, eval_source = source, None
if exec_source is not None:
exec_source += '\n'
if eval_source is not None:
eval_source += '\n'
# create a dedicated module to be used as this statement's __main__
statement_module = new.module('__main__')
# use this request's __builtin__, since it changes on each request.
# this is needed for import statements, among other things.
import __builtin__
statement_module.__builtin__ = __builtin__
# create customized display hook
stringify_func = printer or sstr
def displayhook(arg):
if arg is not None:
__builtin__._ = None
print stringify_func(arg)
__builtin__._ = arg
old_displayhook = sys.displayhook
sys.displayhook = displayhook
# swap in our custom module for __main__. then unpickle the session
# globals, run the statement, and re-pickle the session globals, all
# inside it.
old_main = sys.modules.get('__main__')
try:
sys.modules['__main__'] = statement_module
statement_module.__name__ = '__main__'
# re-evaluate the unpicklables
for code in session.unpicklables:
exec code in statement_module.__dict__
old_globals = dict(statement_module.__dict__)
# re-initialize the globals
session_globals_dict = session.globals_dict()
for name, val in session_globals_dict.items():
try:
statement_module.__dict__[name] = val
except:
session.remove_global(name)
# re-initialize '_' special variable
__builtin__._ = session_globals_dict.get('_')
# run!
offset = 0
try:
old_stdout = sys.stdout
old_stderr = sys.stderr
try:
if stream is not None:
sys.stdout = stream
sys.stderr = stream
if exec_source is not None:
try:
exec_code = self.compile(exec_source, 'exec')
except (OverflowError, SyntaxError, ValueError):
return self.error(stream, self.syntaxerror())
eval(exec_code, statement_module.__dict__)
if eval_source is not None:
if exec_source is not None:
offset = len(exec_source.split('\n'))
result = eval(eval_source, statement_module.__dict__)
sys.displayhook(result)
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
except:
return self.error(stream, self.traceback(offset))
# extract the new globals that this statement added
new_globals = {}
#.........这里部分代码省略.........
示例8: finished
def finished(outfile):
"""Print a closing message"""
sys.displayhook("Fixed pseudoscaffold can be found at " + os.getcwd() + "/" + outfile)
sys.exit(0)
示例9: eval
def eval(self, id, control_vals, displayhook):
f, controls = self._interacts[id]
assert len(controls) == len(control_vals)
displayhook(f(*[c.eval(v) for c, v in zip(controls, control_vals)]))
示例10: evaluate
def evaluate(self, source):
"""Evaluate a piece of Python source code. """
source = source.replace('\r', '').rstrip()
# XXX: make all this SIGINT aware
if '\n' in source:
exec_source, eval_source = self.split(source)
else:
exec_source, eval_source = None, source
eval_source += '\n'
try:
self.compile(eval_source, 'eval')
except (OverflowError, SyntaxError, ValueError):
if '\n' not in source and self.is_inspect(source):
return self.inspect(source)
exec_source = source
eval_source = None
try:
del self.namespace['__plots__']
except KeyError:
pass
interrupted = False
traceback = False
result = None
start = time.clock()
try:
if exec_source is not None:
try:
exec_code = self.compile(exec_source, 'exec')
except (OverflowError, SyntaxError, ValueError):
traceback = self.syntaxerror()
eval_source = None
else:
eval(exec_code, self.namespace)
if eval_source is not None:
result = eval(eval_source, self.namespace)
sys.displayhook(result)
except SystemExit:
raise
except KeyboardInterrupt:
traceback = self.traceback()
interrupted = True
except:
traceback = self.traceback()
end = time.clock()
try:
plots = self.namespace['__plots__']
except KeyError:
plots = []
self.index += 1
if result is not None:
self.namespace['_%d' % self.index] = result
self.namespace['___'] = self.namespace.get('__')
self.namespace['__'] = self.namespace.get('_')
self.namespace['_'] = result
result = {
'source': source,
'index': self.index,
'time': end - start,
'plots': plots,
'traceback': traceback,
'interrupted': interrupted,
}
return result
示例11: __call__
def __call__(self, tp, val, argin3):
global _auto_quote_funcs_
# We only handle SyntaxErrors
if not isinstance(val, exceptions.SyntaxError):
self._orig_ehook(tp, val, argin3)
return
# Complain if we're not at the top level
if (val.text[0]).isspace():
raise RuntimeError, "LazyPython shortcuts do not work in loops or functions."
# Test for shell escape
if val.text[0] == _SHELL_ESCAPE:
os.system(val.text[1:])
return
# 0 -> normal exception, 1 -> auto-quote, 2 -> auto-paren
lp_mode = 0
iFun = _first_word_re_.match(val.text)
if iFun is None: # Hard to see how this could happen, but just in case
self._orig_ehook(tp, val, argin3)
return
iFun = iFun.group(0)[:-1]
if val.text[0] == _PAREN_ESCAPE:
# Check for the auto-paren escape
lp_mode = 2
iFun = iFun[1:]
text = val.text[1:]
elif val.text[0] == _QUOTE_ESCAPE:
# Check for the auto-quote escape
lp_mode = 1
iFun = iFun[1:]
text = val.text[1:]
else:
# See if it's an auto-quote/paren function or a callable
text = val.text
if iFun in _auto_quote_funcs_:
lp_mode = 1
elif iFun in _auto_paren_funcs_:
lp_mode = 2
else:
try:
if callable(eval(iFun, _ns_)):
lp_mode = 2
except:
lp_mode = 0
# Now decide what to do based on lp_mode
if lp_mode == 0:
# Normal Exception
self._orig_ehook(tp, val, argin3)
return
if lp_mode == 1:
theRest = text[len(iFun) :].strip()
# Auto-quote
newcmd = iFun + '("' + '", "'.join(theRest.split()) + '")\n'
elif lp_mode == 2:
# Auto-paren
# newcmd = iFun + '(' + ','.join(theRest.split()) + ')\n'
theRest = text[len(iFun) :].strip()
newcmd = iFun + "(" + theRest + ")\n"
elif lp_mode == 3:
pass # newcmd has already been set
else:
raise RuntimeError, "Error in LazyPython.py! Illegal lp_mode."
# Try to execute the new command
try:
print "-->", newcmd
sys.displayhook(eval(newcmd, _ns_))
# exec newcmd in _ns_
except:
traceback.print_exc()
示例12: loop
def loop(self):
while True:
try:
if self.readMore:
sys.stdout.write("... ")
sys.stdout.flush()
self.single_input += sys.stdin.readline()
else:
sys.stdout.write(">>> ")
sys.stdout.flush()
self.single_input = sys.stdin.readline()
input_stream = antlr4.InputStream(self.single_input)
# Instantiate and run generated lexer
self.lexer = CustomLexer(input_stream)
self.tokens = antlr4.CommonTokenStream(self.lexer)
# Setting up error handling stuff
error_handler = CustomErrorStrategy()
error_listener = CustomErrorListener()
buffered_errors = BufferedErrorListener()
error_listener.addDelegatee(buffered_errors)
# Run parser and set error handler
self.parser = TinyPyParser(self.tokens)
self.parser._errHandler = error_handler
# Remove default terminal error listener & and our own
self.parser.removeErrorListeners()
self.parser.addErrorListener(error_listener)
# Parse input
parse_tree = self.parser.single_input()
# Determine what to do next
if error_listener.eof_received:
print()
exit(0)
elif error_listener.input_unfinished or self.lexer.opened > 0:
# User has not finished his input yet, read the next line and repeat
self.readMore = True
continue
elif error_listener.errors_encountered > 0:
# Errors encountered, start over
print(buffered_errors.buffer)
self.readMore = False
continue
else:
# Successfully parsed the input, next time start over
self.readMore = False
# Build a flattened syntax tree
cst = CST.CstFiltered(tree=parse_tree)
# Print some stuff... (if needed)
if self.args.cst:
print(cst)
if self.args.parse_tree:
parseTreeString = Trees.toStringTree(parse_tree, recog=self.parser)
print(parseTreeString)
# Evaluate it...
visitor = CustomVisitor()
ast = visitor.visitSingle_input(parse_tree)
if ast == None:
continue
if self.args.parse_only:
continue
results = ast.eval()
#
# ast.eval() returns list of statements; loop through them and print
#
if results != None:
for statement in results:
if statement != None and not isinstance(statement, ControlFlowMark):
sys.displayhook(statement)
#if results != None:
# sys.displayhook(results)
except KeyboardInterrupt as e:
print("")
exit(0)
except antlr4.RecognitionException as e:
print("Caught" + str(e) )
except runtime.Errors.BaseRuntimeException as e:
print(e.__class__.__name__ + ": " + str(e))
except SystemExit as e:
sys.exit(e)
except BaseException as e:
print(e.__class__.__name__ + ": " + str(e))
示例13: random_ints
# -*- coding:utf-8 -*-
from sympy import pprint
from sympy import Symbol
from sympy.matrices import *
from random import *
import sys
sys.displayhook(pprint)
import time
import numpy as np
import matplotlib.pyplot as plt
print '''
****************************************************************************
6. Estime a complexidade do algoritmo de solução de sistemas lineares do pacote computacional de sua
preferência: registre os tempos que o pacote levou para resolver sistemas aleatórios nxn, com n =
16; 32; 64; 128; 256; 512; 1024; 2048. Faça um gráfico do log do número de colunas contra o log dos tempos
registrados. O algoritmo do pacote tem complexidade inferior a O(nˆ3)?
'''
def random_ints(num, lower=-100, upper=100):
return [randrange(lower,upper+1) for i in range(num)]
def geraMatriz(n, l=-100, u=100):
return Matrix(n, n, random_ints(n**2, l, u))
tempoGeracao = {}
tempoDeterminante = {}
for n in range(4,11):
''' Contagem de tempo para criação das matrizes '''
示例14: print
print(sys.modules) # 打印系统所有模块,字典形式返回
# print(sys.exit(2)) # 打印程序返回代码
print(sys.version) # 打印python版本
print(sys.maxsize) # 打印最大值
print(sys.path) # 返回当前PYTHONPATH环境变量
print(sys.platform) # 返回操作系统平台名称
print(sys.stdout.write("inpu9t")) # 返回标准输出长度
# print(sys.stdin.readlin()[:-1]) # 标准输入,并分片取开头到倒数第一个(不包含)的内容
print(sys.modules.keys()) # 打印所有模块名
print(sys.modules.values()) # 打印所有模块位置
print(sys.exc_info()) # 获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息
print(sys.hexversion) # 获取十六进制的版本值
print(sys.api_version) # 获取Cpython API版本
print(sys.version_info) # 打印版本详细信息
print(
sys.displayhook(2)
) # 如果value非空,这个函数会把他输出到sys.stdout,并且将他保存进__builtin__._.指在python的交互式解释器里,’_’ 代表上次你输入得到的结果,hook是钩子的意思,将上次的结果钩过来
print(sys.getdefaultencoding()) # 获取当前默认编码格式
print(sys.getfilesystemencoding()) # 获取文件系统编码
print(sys.builtin_module_names) # 打印内置模块名
print(sys.executable) # 打印python解释权程序路径
print(sys.getprofile())
print(sys.getallocatedblocks())
# print(sys.copyright) # 打印python版权信息
print(sys.byteorder) # 本地字节规则的指示器,big-endian平台的值是’big’,little-endian平台的值是’little’
# print(sys.exc_value)
print(sys.stdin) # 标准输入
print(sys.stdout) # 标准输出
print(sys.stderr) # 标准错误输出
print(sys.maxunicode) # 打印最大unicode值
示例15: evaluate
def evaluate(self, source):
"""Evaluate a piece of Python source code. """
source = source.replace('\r', '').rstrip()
# XXX: make all this SIGINT aware
if '\n' in source:
exec_source, eval_source = self.split(source)
else:
exec_source, eval_source = None, source
eval_source += '\n'
try:
self.compile(eval_source, 'eval')
except (OverflowError, SyntaxError, ValueError):
if '\n' not in source and self.is_inspect(source):
return self.inspect(source)
exec_source = source
eval_source = None
# If in debug mode, then don't setup output trap so that we can
# run a debugger (e.g. pdb). Note that stdout and stderr won't
# be captured and stored in the resulting dict object.
if not self.debug:
self.trap.set()
try:
try:
del self.locals['__plots__']
except KeyError:
pass
interrupted = False
traceback = False
result = None
start = time.clock()
try:
if exec_source is not None:
try:
exec_code = self.compile(exec_source, 'exec')
except (OverflowError, SyntaxError, ValueError):
traceback = self.syntaxerror()
eval_source = None
else:
exec exec_code in self.locals
if eval_source is not None:
result = eval(eval_source, self.locals)
sys.displayhook(result)
except SystemExit:
raise
except KeyboardInterrupt:
traceback = self.traceback()
interrupted = True
except:
traceback = self.traceback()
end = time.clock()
try:
plots = self.locals['__plots__']
except KeyError:
plots = []
self.index += 1
if result is not None:
self.locals['_%d' % self.index] = result
self.locals['___'] = self.locals.get('__')
self.locals['__'] = self.locals.get('_')
self.locals['_'] = result
result = {
'source': source,
'index': self.index,
'time': end - start,
'out': self.trap.out,
'err': self.trap.err,
'plots': plots,
'traceback': traceback,
'interrupted': interrupted,
}
if traceback:
result['traceback_html'] = self.highlight.traceback(traceback)
return result
finally:
self.trap.reset()