我正在构建一个基于Raspberry Pi的无屏幕长期艺术装置。 Text-to-Speech on the Raspberry pi的一个常见应用是人们配置他们的Pis在启动时说出他们的IP地址以简化SSH。
我已经爱上了日志记录模块。永远不再评论无数的印刷陈述让我的心发光。对于我的情况,有一个说出错误消息的日志记录处理程序是理想的。我目前使用的StreamHandler和FileHandler非常适合开发和问题后诊断,但对于原位问题解决却很糟糕。此外,有一些令人愉快的SciFi关于我的机器人在向我大喊大叫错误。
I found an example of a custom handler for SMS-based error logging,并尝试通过电子发言实现我自己。它说话,但整个节目在第一个口语句末结束时停止。
我正在寻找有关如何实现不阻止程序执行的流处理程序的建议。 我破坏的自定义处理程序:
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 )
答案 0 :(得分:0)
我知道这是在很久以前就被问过了 - 我在发布时错过了它并偶然发现了它。以下适用于我:
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())
当我跑步时,我听到“你好”,然后说“再见”。