首页 > 解决方案 > 如何让命令行连续打印日志信息?

问题描述

我写了一个简单的应用程序,我想每秒钟打印一次日志消息。我打开一个终端并运行它,它运行良好。Enter但是当我使用鼠标单击终端时,除非我在终端中打印,否则它不会打印日志消息。

编码

import logging
from PyQt5.QtCore import *

logging.basicConfig(level=logging.DEBUG)


app = QCoreApplication([])

timer = QTimer()
timer.setInterval(1000)
timer.timeout.connect(lambda: logging.info("abc"))
timer.start()

app.exec()

标签: python-3.xterminalpyqt5

解决方案


好像是环境问题。下面的示例演示了即使按下鼠标按钮,Qt 日志记录也能正常工作。

cat pyqt_logging_ex.py
#!/usr/bin/python3.9
import logging,os
from PyQt5.QtCore import *
from pynput import mouse,keyboard

def on_click(x, y, button, pressed):
    print("Mouse click")

def on_press(key):
    print("Key pressed, exiting")
    os._exit(0)

listener = keyboard.Listener(on_press=on_press)
listener.start()
listener = mouse.Listener(on_click=on_click)
listener.start()
print("Started listeners")

logging.basicConfig(level=logging.DEBUG)
app = QCoreApplication([])
timer = QTimer()
timer.setInterval(1000)
timer.timeout.connect(lambda: logging.info("abc"))
timer.start()
app.exec()

运行示例:

pyqt_logging_ex.py
Started listeners
INFO:root:abc
INFO:root:abc
INFO:root:abc
Mouse click
Mouse click
INFO:root:abc
INFO:root:abc
Mouse click
Mouse click
INFO:root:abc
INFO:root:abc
qKey pressed, exiting

我的环境:

uname -or ; lsb_release -d ; python3.9 --version
4.4.0-19041-Microsoft GNU/Linux
Description:    Ubuntu 20.04.3 LTS
Python 3.9.5

推荐阅读