且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将Python的日志输出重定向到Kivy标签?

更新时间:2023-10-07 08:20:16

我总是使自己的日志记录。 / p>

这是一个工作示例:



main.py:

  import kivy 
from kivy.app import App
from kivy.clock import Clock
from kivy.uix .label import Label
import logging
import thread
import time

def my_thread(log):

for i in range(2 **
time.sleep(1)
log.info(WOO%s,i)

class MyLabelHandler(logging.Handler):

def __init __(self,label,level = logging.NOTSET):
logging.Handler .__ init __(self,level = level)
self.label = label

def emit(self,record):
使用Kivy主循环线程安全的Clock模块
def f(dt = None):
self.label.text = self.format(record)#use + = to append ...
Clock.schedule_once(f)


class MyApp(App):
def build(self):
label = Label(text =显示日志在这里)

log = logging .getLogger(my.logger)
log.level = logging.DEBUG
log.addHandler(MyLabelHandler(label,logging.DEBUG))

thread.start_new(my_thread ,(log,))

返回标签


如果__name__ =='__main__':
MyApp()。run()

注意这里的简单线程来测试日志记录。


As written in the title , i need to redirect the logging module output to a Kivy label in the simple way possible. I searched for a solution on the web an i think the best methods are to overwrite the StreamHandler or the MemoryHandler in some way (but i don't know how to do this point).

Someone can help me to achieve this?

I use python 2.7

thanks

I always make my own logging.Handler for cases like these.

Here is a working example:

main.py:

import kivy
from kivy.app import App
from kivy.clock import Clock
from kivy.uix.label import Label
import logging
import thread
import time

def my_thread(log):

    for i in range(2**20):
        time.sleep(1)
        log.info("WOO %s", i)

class MyLabelHandler(logging.Handler):

    def __init__(self, label, level=logging.NOTSET):
        logging.Handler.__init__(self, level=level)
        self.label = label

    def emit(self, record):
        "using the Clock module for thread safety with kivy's main loop"
        def f(dt=None):
            self.label.text = self.format(record) #"use += to append..."
        Clock.schedule_once(f)


class MyApp(App):
    def build(self):
        label = Label(text="showing the log here")

        log = logging.getLogger("my.logger")
        log.level = logging.DEBUG
        log.addHandler(MyLabelHandler(label, logging.DEBUG))

        thread.start_new(my_thread, (log,))

        return label


if __name__ == '__main__':
    MyApp().run()

Notice the simple thread here to test the logging.