Python服务 - 用时间戳写入文件名

问题描述:

我写了一个无限期运行的Python脚本。它使用PyInotify监视目录,并使用Multiprocessing模块通过外部脚本运行在这些目录中创建的任何新文件。这一切都很好。Python服务 - 用时间戳写入文件名

我遇到的问题是将输出写入文件。我选择的文件名使用当前日期(使用datetime.now),理论上应该每小时滚动一小时。

now = datetime.now() 
filename = "/data/db/meta/%s-%s-%s-%s.gz" % (now.year, now.month, now.day, now.hour) 
with gzip.open(filename, 'ab') as f: 
    f.write(json.dumps(data) + "\n") 
    f.close() #Unsure if I need this, here for debug 

不幸的是,当小时滚动时 - 输出停止并且从不返回。没有例外,它只是停止工作。

total 2.4M 
drwxrwxr-x 2 root root 4.0K Sep 8 08:01 . 
drwxrwxr-x 4 root root 12K Aug 29 16:04 .. 
-rw-r--r-- 1 root root 446K Aug 29 16:59 2016-8-29-16.gz 
-rw-r--r-- 1 root root 533K Aug 30 08:59 2016-8-30-8.gz 
-rw-r--r-- 1 root root 38K Sep 7 10:59 2016-9-7-10.gz 
-rw-r--r-- 1 root root 95K Sep 7 14:59 2016-9-7-14.gz 
-rw-r--r-- 1 root root 292K Sep 7 15:59 2016-9-7-15.gz #Manually run 
-rw-r--r-- 1 root root 834K Sep 8 08:59 2016-9-8-8.gz 

这些文件是不是真的属于root,只是改变了他们对公共消费

正如你所看到的,所有的时间标记结束的文件:59接下来的一小时从未发生。

在做这件事情时,我是否应该考虑一些事情?有没有我缺少的无限期运行Python脚本?


经过一番窥视。 PyInotify似乎是我的问题。 这里(https://unix.stackexchange.com/questions/164794/why-doesnt-inotifywatch-detect-changes-on-added-files

我调整了您的代码,每分钟更改一次文件名,这加快了调试的速度,但仍然测试了这个假设。

import datetime 
import gzip, time 
from os.path import expanduser 
while True: 
    now = datetime.datetime.now() 
    filename = expanduser("~")+"/%s-%s-%s-%s-%s.gz" % (now.year, now.month, now.day, now.hour, now.minute) 
    with gzip.open(filename, 'a') as f: 
     f.write(str(now) + "\n") 
     f.write("Data Dump here" + "\n") 
    time.sleep(10) 

这似乎运行没有问题。改变我的电脑的时区也被拿起并处理。鉴于上述情况,我怀疑您的错误可能存在于别处,并且需要在关键点进行一些明智的调试值打印。尝试使用上面更细化的文件名来加速调试。

+0

我怀疑你是对的。它可能与PyInotify代码本身有关。我将使用你的代码来帮助调试。 – gleb1783

+0

看到更新 - 你是对的。 – gleb1783

+0

很高兴听到您破解它 - 感谢您的更新! –