gpt4 book ai didi

python - 如何管理登录 curses

转载 作者:太空狗 更新时间:2023-10-29 17:45:23 26 4
gpt4 key购买 nike

我使用 curses 为我的应用程序创建了一个简单的 UI,我还使用层级结构(logmain、logmain.child1)等在我的模块中包含日志(日志记录)。

如果发生日志事件,日志将显示在我的 UI 中,破坏其外观。我还创建了一个 pad (myLogPad) 以便将传入的日志放在那里,但没有成功。我如何拦截日志事件并将其打印在屏幕的特定区域(最后一行)?

def setupLogger(name,file_name):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
#formatter = logging.Formatter(
# "%(asctime)s %(threadName)-11s %(levelname)-10s %(message)s")
formatter = logging.Formatter('%(asctime) -25s - %(name) -15s - %(levelname) -10s - %(message)s')
formatterDisplay = logging.Formatter('%(asctime)-8s|%(name)-12s|%(levelname)-6s|%(message)-s', '%H:%M:%S')
# Alternative formatting available on python 3.2+:
# formatter = logging.Formatter(
# "{asctime} {threadName:>11} {levelname} {message}", style='{')

# Log to file
filehandler = logging.FileHandler(file_name, 'w')

filehandler.setFormatter(formatter)
logger.addHandler(filehandler)

# Log to stdout too
streamhandler = logging.StreamHandler()

streamhandler.setFormatter(formatterDisplay)
logger.addHandler(streamhandler)

我尝试在 streamhandler = logging.StreamHandler() 中传递 mylog pad 但没有成功。任何想法?谢谢

最佳答案

您可以创建自己的 Handler 类以将日志消息发送到 curses pad 或窗口:

try:
unicode
_unicode = True
except NameError:
_unicode = False

class CursesHandler(logging.Handler):
def __init__(self, screen):
logging.Handler.__init__(self)
self.screen = screen
def emit(self, record):
try:
msg = self.format(record)
screen = self.screen
fs = "\n%s"
if not _unicode: #if no unicode support...
screen.addstr(fs % msg)
screen.refresh()
else:
try:
if (isinstance(msg, unicode) ):
ufs = u'\n%s'
try:
screen.addstr(ufs % msg)
screen.refresh()
except UnicodeEncodeError:
screen.addstr((ufs % msg).encode(code))
screen.refresh()
else:
screen.addstr(fs % msg)
screen.refresh()
except UnicodeError:
screen.addstr(fs % msg.encode("UTF-8"))
screen.refresh()
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)

(这基本上是从 logging.StreamHandler 复制的。)需要初始化窗口或 pad 以允许自动滚动等:

screen.nodelay(1)
maxy, maxx = screen.getmaxyx()
begin_x = 2; begin_y = maxy-5
height = 5; width = maxx-4
win = curses.newwin(height, width, begin_y, begin_x)
curses.setsyx(-1, -1)
screen.addstr("Testing my curses app")
screen.refresh()
win.refresh()
win.scrollok(True)
win.idlok(True)
win.leaveok(True)
mh = CursesHandler(win)
mh.setFormatter(formatterDisplay)
logger.addHandler(mh)

这里,screen 是主要的 curses 屏幕。

关于python - 如何管理登录 curses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27774093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com