我正在使用 ipython 笔记本。我在调试时使用了很多打印语句,但有时我不小心打印了太多,导致我的电脑死机。如果你要打印超过 10000 个字符,有没有办法打开告诉 python 给你警告的东西?
更新: 感谢大家的精彩想法。我会调查日志记录。
请您参考如下方法:
在 Python 3 中,您可以根据需要替换 print 函数(大概是在模块级别),就像这样。
_print = print
def print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False):
# this test could probably be more sophisticated, to test for
# any file whose file descriptor is the same as stdout or stderr
if file in (sys.stdout, sys.stderr):
output = io.StringIO()
_print(*objects, sep=sep, end=end, file=output)
data = output.getvalue()
if len(data) > 10000:
# do the "are you sure?" interaction, however you want that to work
_print(data, end='', file=file, flush=flush)
else:
_print(*objects, sep=sep, end=end, file=file, flush=flush)
老实说,您可能不想乱用内置函数,尽管您可以。但不管你怎么称呼,原理都是一样的。
在 Python 2 中,print 不采用相同的选项(而且它是一个关键字,因此您无法拦截它,即使您愿意也无法调用您的函数)。因此,您可以编写一个功能类似于 Python 3 print 的函数,但要么使用 Python 2 print 作为底层机制,要么执行 from __future__ import print_function .此外,StringIO 位于名为 StringIO 的模块中,而不是 io。
