簡體   English   中英

如果要打印超過1000行,如何向python添加一些內容以發出警告

[英]how to add something to python to give you a warning if you're about to print over 1000 lines

我正在使用ipython筆記本。 在調試時,我會使用很多打印語句,但是有時我偶然打印了太多內容,這凍結了我的計算機。 如果您要打印超過10000個字符,是否有辦法打開一個告訴python的警告?

更新:謝謝大家的出色想法。 我將研究日志記錄。

如果不編寫自己的打印包裝函數,就沒有簡單的方法來限制打印輸出。 但是更好的主意(而不是使用print)是使用python日志記錄系統進行調試語句,然后將輸出重定向到文件。

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

在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

def mprint(*args,**kwargs):
   max_length = kwargs.get("max_length",1000)
   out_stream = kwargs.get("out",sys.stdout)
   s= " ".join(str(x) for x in args)
   half_of_max = max_length/2
   if len(s) > max_length:
       print "too much to print: %s...%s"%(s[:half_of_max ],s[max(len(s)-half_of_max ,half_of_max ):])
       return
   out_stream.write(s)

而不是

print "hello world"
mprint("hello world",max_length=4)

或寫入文件

with open("asd.txt","w") as f:
    mprint("hello world",max_length=4,out=f)

這還具有插入數據的附加功能...例如,如果您想在打印之前插入時間戳或稱為打印的行

實際上,我在所有日志記錄中都使用了類似的功能(但是out是全局設置的,而不是在調用時設置)

盡管使用實際日志記錄包的建議也是一個不錯的建議:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM