[英]How to get non-blocking/real-time behavior from Python logging module? (output to PyQt QTextBrowser)
[英]Audible Errors - Custom non-blocking text-to-speech handler for Python's logging module
我正在構建一個基於Raspberry Pi的無屏幕長期藝術裝置。 Raspberry pi上的文本到語音的常見應用是人們配置他們的Pis在啟動時說出他們的IP地址以簡化SSH。
我已經愛上了日志記錄模塊。 永遠不再評論無數的印刷陳述讓我的心發光。 對於我的情況,有一個說出錯誤消息的日志記錄處理程序是理想的。 我目前使用的StreamHandler和FileHandler非常適合開發和問題后診斷,但對於原位問題解決卻很糟糕。 此外,有一些令人愉快的SciFi關於我的機器人在向我大喊大叫錯誤。
我找到了一個基於SMS的錯誤記錄的自定義處理程序的示例,並嘗試使用e-speak實現我自己的。 它說話,但整個節目在第一個口語句末結束時停止。
我正在尋找有關如何實現不阻止程序執行的流處理程序的建議。 破碎的自定義處理程序
import logging
import os
#based on SMSHandler http://pantburk.info/?blog=77
def speak(stringToSay):
'''say whatver it is told to say, squleching annoying warnings'''
stringToSay = "'"+stringToSay+"'"
#English female voice, emphasis on capitals (-k), speaking slowly (-s) using direct text:-
#the 2>/dev/null' is there because any calls to the rPi audio card result in a dozen warnings.
# see: http://raspberrypi.stackexchange.com/questions/3412/errors-with-espeak
os.system('espeak -ven+f3 -k5 -s150 '+stringToSay+' 2>/dev/null')
class TALKHandler(logging.Handler): # Inherit from logging.Handler
def __init__(self):
# run the regular Handler __init__
logging.Handler.__init__(self)
def emit(self, record):
# record.message is the log message
speak(record.message)
來自正在記錄的程序的片段:
logging.handlers.TALKHandler = speechHandler.TALKHandler
# create the handler object
talkingHandler = logging.handlers.TALKHandler()
# Configure the handler to only send SMS for critical errors
talkingHandler.setLevel(logging.CRITICAL)
# and finally we add the handler to the logging object
logger.addHandler(talkingHandler)
ipAddress = [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
ipAddress = " ".join(ipAddress)
ipAddress = ipAddress.replace(".","dot")
logger.critical("Current IP Address is " + ipAddress )
我知道這是在很久以前被問過的 - 我在發布時錯過了它並偶然發現了它。 以下適用於我:
import logging
import subprocess
import sys
class TalkHandler(logging.Handler):
def emit(self, record):
msg = self.format(record)
cmd = ['espeak', '-ven+f3', '-s150', msg]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
p.communicate()
def configure_logging():
h = TalkHandler()
root = logging.getLogger()
root.addHandler(h)
root.setLevel(logging.DEBUG)
def main():
logging.info('Hello')
logging.debug('Goodbye')
if __name__ == '__main__':
configure_logging()
sys.exit(main())
當我運行它時,我聽到“你好”,然后說“再見”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.