我有来自COM端口的输出流,我希望将其保存到文件中,每隔10秒新文件。
我可以像这样读取COM端口:
import sys
import datetime, threading
for line in sys.stdin:
print(line)
my_writing_function(line)
我需要每10秒更改一次文件名,所以,我可能需要这样的东西:
def filename():
# if already opened -> close.
filename='{0:%Y-%m-%d_%H:%M:%S}'.format(datetime.datetime.now())
fh = open(filename, "a+")
threading.Timer(10, filename).start()
但在这种情况下,fh应该是全局的.. 可能我需要制作一些旗帜并在写作前检查它吗?
感谢。
答案 0 :(得分:0)
import sys
import logging
import time
import datetime
from 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')
for line in sys.stdin:
logger.info(line)
# raise Exception
except Exception as 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)