Save output to new file every 10 seconds in Python 3 -
i have output flow com-port , want save files, @ every 10 second new file.
i can read com-port this:
import sys import datetime, threading line in sys.stdin: print(line) my_writing_function(line)
i need change filename every 10 seconds, so, need this:
def filename(): # if opened -> close. filename='{0:%y-%m-%d_%h:%m:%s}'.format(datetime.datetime.now()) fh = open(filename, "a+") threading.timer(10, filename).start()
but in case fh should global.. may need make flag , check before writing?
thanks.
import sys import logging import time import datetime logging.handlers import timedrotatingfilehandler #---------------------------------------------------------------------- def create_timed_rotating_log(path): logger = logging.getlogger("rotating log") logger.setlevel(logging.info) handler = timedrotatingfilehandler(path, when="s", interval=2, backupcount=0) logger.addhandler(handler) while true: try: print('while loop start') line in sys.stdin: logger.info(line) # raise exception except exception e: print(str(datetime.datetime.now().strftime('%y-%m-%d %h:%m:%s')) + '\n' +str(e)) #---------------------------------------------------------------------- if __name__ == "__main__": log_file = "log" create_timed_rotating_log(log_file)
Comments
Post a Comment