我正在寻找一种方法来覆盖和解析Python REPL中的所有输出:例如终端中的python / IPython,qtconsole。
通过覆盖打印功能,这对于打印文本来说非常简单。对于一个简单的例子,假设我们想为所有输出添加一个惊叹号:
orig_print = print
print = lambda text: orig_print(text + '!')
现在所有打印命令都会添加感叹号。这可以通过以下方式重置:
del print
我的问题:如何进行REPL输出的等效操作?例如,我怎样才能这样做呢?
In[1]: 5 + 5
Out[2]: 10!
搜索引导我走上了contextlib,subprocess和sys.stdout的路径,但我还没有找到解决方案。在Github检查了sympy的打印模块,没有成功。
我只是尝试覆盖sys.stdout.write
并且它有效(有一些怪癖)。如果我错了,有人会纠正我,但我认为这不会比这更好。
In [1]: import sys
In [2]: tmp = sys.stdout.write
In [3]: sys.stdout.write = lambda text: tmp(text + '!')
In [4]: 5 + 5
!Out[4]: 10!
!!
!!In [5]:
编辑:
我已经走到了这一步。还没弄清楚那1个额外的!
来自哪里。
In [5]: sys.stdout.write = lambda text: tmp(text if text.endswith('\n') else text + '!\r')
In [6]: 5+5
Out[6]: 10!
!
In [7]:
一个适用于IPython QtConsole的示例,基于this article。这与orangeink的覆盖stdout的解决方案一起使用:
class SciNum:
"""For compatibility with IPython's pretty printer: Contains a string,
with a REPR that allows pretty() to print without quotes, as it would
if using the string directly."""
def __init__(self, text: str):
self.text = text
def __repr__(self):
return self.text
def _print_ipython(arg, p, cycle) -> None:
"""Uses IPython's pretty printer to modify output for a qtconsole or notebook;
stdout doesn't seem to work for them."""
p.text(IPython.lib.pretty.pretty(SciNum(format(arg))))
def start() -> None:
if not ipython_exists:
return
ip = IPython.get_ipython()
# We only need to handle IPython separately if in a Qtconsole or Notebook.
if isinstance(ip, IPython.terminal.interactiveshell.TerminalInteractiveShell):
return
text_formatter = ip.display_formatter.formatters['text/plain']
text_formatter.for_type(float, _print_ipython)
text_formatter.for_type(int, _print_ipython)