花了一些时间重定向stdout并将输出记录到tkinter文本小部件,我已经决定需要一些帮助。我的代码如下:
#!/usr/bin/env python
from Tkinter import *
import logging
from threading import Thread
class IODirector(object):
def __init__(self,text_area):
self.text_area = text_area
class StdoutDirector(IODirector):
def write(self,str):
self.text_area.insert(END,str)
def flush(self):
pass
class App(Frame):
def __init__(self, master):
self.master = master
Frame.__init__(self,master,relief=SUNKEN,bd=2)
self.start()
def start(self):
self.master.title("Test")
self.submit = Button(self.master, text='Run', command=self.do_run, fg="red")
self.submit.grid(row=1, column=2)
self.text_area = Text(self.master,height=2.5,width=30,bg='light cyan')
self.text_area.grid(row=1,column=1)
def do_run(self):
t = Thread(target=print_stuff)
sys.stdout = StdoutDirector(self.text_area)
t.start()
def print_stuff():
logger = logging.getLogger('print_stuff')
logger.info('This will not show')
print 'This will show'
print_some_other_stuff()
def print_some_other_stuff():
logger = logging.getLogger('print_some_other_stuff')
logger.info('This will also not show')
print 'This will also show'
def main():
logger = logging.getLogger('main')
root = Tk()
app = App(root)
root.mainloop()
if __name__=='__main__':
main()
我知道可以根据文本小部件定义新的日志记录处理程序,但我无法使其正常工作。函数“print_stuff”实际上只是围绕许多不同函数的包装器,它们都设置了自己的记录器。我需要帮助定义一个“全局”的新日志处理程序,以便可以从具有自己的记录器的每个函数中实例化它。非常感谢任何帮助。
答案 0 :(得分:4)
只是为了确保我理解正确:
您希望将日志消息打印到STDout和Tkinter文本小部件,但日志记录不会在标准控制台中打印。
如果这确实是你的问题,那么该怎么做。
首先让我们在Tkinter中创建一个非常简单的控制台,它可以是任何文本小部件,但我将它包括在内以保证完整性:
class LogDisplay(tk.LabelFrame):
"""A simple 'console' to place at the bottom of a Tkinter window """
def __init__(self, root, **options):
tk.LabelFrame.__init__(self, root, **options);
"Console Text space"
self.console = tk.Text(self, height=10)
self.console.pack(fill=tk.BOTH)
现在让我们覆盖日志处理程序以重定向到参数中的控制台,并仍然自动打印到STDout:
class LoggingToGUI(logging.Handler):
""" Used to redirect logging output to the widget passed in parameters """
def __init__(self, console):
logging.Handler.__init__(self)
self.console = console #Any text widget, you can use the class above or not
def emit(self, message): # Overwrites the default handler's emit method
formattedMessage = self.format(message) #You can change the format here
# Disabling states so no user can write in it
self.console.configure(state=tk.NORMAL)
self.console.insert(tk.END, formattedMessage) #Inserting the logger message in the widget
self.console.configure(state=tk.DISABLED)
self.console.see(tk.END)
print(message) #You can just print to STDout in your overriden emit no need for black magic
希望它有所帮助。
答案 1 :(得分:2)
这是一个完全修改过的答案,可以满足您的需求。我试图指出问题中代码的哪些行已更改以及添加了新行。
默认情况下,内置logger.StreamHandler
处理程序类将消息输出到sys.stderr
,因此要让它们重定向sys.stdout
文本小部件需要使用自定义控制台处理程序集构建新的记录器做到这一点。由于您希望将此设置应用于模块中的所有记录器,因此需要将此设置应用于无名“root”记录器,以便所有其他命名记录器从其继承其设置。
from Tkinter import *
import logging
from threading import Thread
class IODirector(object):
def __init__(self, text_area):
self.text_area = text_area
class StdoutDirector(IODirector):
def write(self, msg):
self.text_area.insert(END, msg)
def flush(self):
pass
class App(Frame):
def __init__(self, master):
self.master = master
Frame.__init__(self, master, relief=SUNKEN, bd=2)
self.start()
def start(self):
self.master.title("Test")
self.submit = Button(self.master, text='Run', command=self.do_run, fg="red")
self.submit.grid(row=1, column=2)
self.text_area = Text(self.master, height=2.5, width=30, bg='light cyan')
self.text_area.grid(row=1, column=1)
def do_run(self):
t = Thread(target=print_stuff)
sys.stdout = StdoutDirector(self.text_area)
# configure the nameless "root" logger to also write # added
# to the redirected sys.stdout # added
logger = logging.getLogger() # added
console = logging.StreamHandler(stream=sys.stdout) # added
logger.addHandler(console) # added
t.start()
def print_stuff():
logger = logging.getLogger('print_stuff') # will inherit "root" logger settings
logger.info('This will now show') # changed
print 'This will show'
print_some_other_stuff()
def print_some_other_stuff():
logger = logging.getLogger('print_some_other_stuff') # will inherit "root" logger settings
logger.info('This will also now show') # changed
print 'This will also show'
def main():
logging.basicConfig(level=logging.INFO) # enable logging # added
root = Tk()
app = App(root)
root.mainloop()
if __name__=='__main__':
main()