【问题标题】:Output difference between ipython and pythonipython和python之间的输出差异
【发布时间】:2020-11-30 20:38:21
【问题描述】:

据我了解,python 将打印输出的repr,但显然并非总是如此。例如:

在 ipython 中:

In [1]: type([])
Out[1]: list

In [2]: set([3,1,2])
Out[2]: {1, 2, 3}

在python中:

>>> type([])
<type 'list'>
>>> set([3,1,2])
set([1, 2, 3])

ipython 对输出应用什么转换?

【问题讨论】:

  • ipython 1.1.0 on python 2.7.5

标签: python ipython read-eval-print-loop repr


【解决方案1】:

IPython 使用IPython.lib.pretty.RepresentationPrinter.pretty 方法代替repr 或标准pprint 模块print the output

模块IPython.lib.pretty 提供了两个在后台使用RepresentationPrinter.pretty 的函数。

IPython.lib.pretty.pretty函数返回一个对象的字符串表示:

>>> from IPython.lib.pretty import pretty
>>> pretty(type([]))
'list'

IPython.lib.pretty.pprint 函数打印对象的表示:

>>> from IPython.lib.pretty import pprint
>>> pprint(type([]))
list

IPython 使用自己的漂亮打印机,因为标准 Python pprint 模块“不允许开发人员提供自己的漂亮打印回调。”

【讨论】:

  • 是否在某处记录了IPython.lib.pretty.pretty 确实是使用的功能?我做了IPython.lib.pretty.pretty = lambda *args, **kwargs: 'potato',ipython 中的输出没有变化。
  • @wim,很好,我已经编辑了我的答案。 IPython.lib.pretty.RepresentationPrinter.pretty = lambda *args, **kwargs: sys.stdout.write('12') 将为任何输入打印 12。
  • 请注意,只有%pprint 魔法开启时才会出现这种情况。我默认将其关闭,并获取 OP 在常规 Python 提示符下看到的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
相关资源
最近更新 更多