簡體   English   中英

過濾 print() 調用? 在全局或每個模塊級別?

[英]Filter print() calls ? on global or per module level?

我的 utils.py 中有以下用於調試信息的函數...

 say = print
 log = print

我想以這種方式聲明它們,以便我可以打開/關閉它們。 如果可能,以每個模塊為基礎。

假設我想測試一些東西並啟用/禁用打印......

我不想使用日志記錄,因為它太麻煩並且需要更多輸入..

我正在使用它進行快速調試並最終刪除這些打印


在 utils.py

say = print
log = print

def nope(*args, **kwargs): return None

在blah.py

from utils import *
class ABC:
  def abc(self): say(111)

在 ipython 中:

from blah import *
a = ABC()
a.abc()
111
say(222)
222

say = nope
a.abc(111)
111
say(222)
None 

您可以隨時重新定義 say/log 以便以后什么都不做。

Python 3.8.2 (default, Apr 27 2020, 15:53:34)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> say = print
>>> say("hello")
hello
>>> def say(*args, **kwargs):
...  return None
...
>>> say("hello")
>>>

當您不想記錄或喜歡它時,您可以使用sys.stdout.write("\033[K")覆蓋/清除終端上的前一行:

def removeLine(dontWant):
    if dontWant == True:
        sys.stdout.write("\033[K")

其中 dontWant 在模塊或 class 中設置,或者作為一個 glob 或任何基於你想要它的時間,然后在每個日志事件之后調用 removeLine。

最后,這是我寫的:

https://github.com/vsraptor/quick-debug/blob/master/debug.py

快速調試:如果您像我一樣不習慣調試器或日志記錄太麻煩,那么這適合您。

暫無
暫無

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

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