我想让一个写日志的脚本在后台运行,即使我关闭终端;
但是测试中我是用了python generate_log.py 是可以正常写入文件的,
但是当我使用了nohup python generate_log.py 日志文件一直是空
nohup python generate_log.py & 也是空的
nohup python -u generate_log.py & 也是空的
python generate_log.py & 也是空
我是用ps -ef 查看了进程是一直存在的
这是我的源码:
# coding:utf-8 from datetime import * import time def produce_log(): a = datetime.now() a=str(a) log="""{0}-POST /kibana/elasticsearch/_msearch?timeout=30000&ignore_unavailable=true&preference=1447070343481 HTTP/1.1" 200 8352 "https://app.logz.io/kibana/index.html" "Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/45.0.2454.101 Chrome/45.0.2454.101 Safari/537.36" 0.465 0.454""".format(a) with open('test.log', 'a+') as file: for i in range(100000): file.write(a) file.write('\n') time.sleep(60) if __name__ == '__main__': for k in range(33): produce_log()
由于write方法并不直接将数据写入文件,而是先写入内存中特定的缓冲区。当缓冲区满了之后才把内容写到磁盘上。
time.sleep之前调用flush()把缓冲区的内容刷写到磁盘上
... file.write(a) file.write('\n') file.flush() time.sleep(60) ...
# coding:utf-8 import datetime import time import sys def produce_log(): """ 这个方法是有问题的可能跟buffer 有关系 :return: """ with open('test.log', mode='a+') as file: for i in range(10): a = datetime.datetime.now() a = str(a) log = """POST /kibana/elasticsearch/_msearch?timeout=30000&ignore_unavailable=true&preference=1447070343481 HTTP/1.1" 200 8352 "https://app.logz.io/kibana/index.html" "Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/45.0.2454.101 Chrome/45.0.2454.101 Safari/537.36" 0.465 0.454""" file.write(log) file.write('\n') sys.stdout.flush() time.sleep(10) def success(): """ 这样写是没有问题的 :return: """ log = """POST /kibana/elasticsearch/_msearch?timeout=30000&ignore_unavailable=true&preference=1447070343481 HTTP/1.1" 200 8352 "https://app.logz.io/kibana/index.html" "Mozilla/5.0 (X11; Linux armv7l) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/45.0.2454.101 Chrome/45.0.2454.101 Safari/537.36" 0.465 0.454""" for i in range(10): with open('test.log','a+') as file: a=datetime.datetime.now() file.write(str(a)+log) file.write('\n') time.sleep(5) if __name__ == '__main__': success()