0

使用看门狗,我希望它在某个目录中查找更新的文件,如果有更新的文件,它会获取文件名并运行具有文件名的特定脚本并将输出作为 txt 文件发送到不同的目录。当文本文件出现在新目录中时,以某种方式获取文件名并将其设置为变量以进行分析。

前任:

第一个目录 /path/to/first/dir/2017/04/27/nfcapd.20170427 <- 新文件(注意,不是 txt 文件)

运行脚本以使用上面的文件名获取下面该文件中的数据

nfdump - r nfcapd.20170427 > home/users/rmaestas/nfcapd.20170427.txt

文件名存储在一个变量中以与代码一起使用

updated = 'nfcapd.21070427.txt’

filename = ('home/users/rmaestas/') #<-- insert 'updated in directory'
with open(filename, 'r') as infile:    
    next(infile) #Skips the first row, first row is not data.
    for line in infile:#read every line       
        if "Summary:" in line:#End of the data, last4 lines are a summary which won't be needed.
            break
        print(line.split()[4].rsplit(':', 1)[0])

#more code... 
4

1 回答 1

3

您需要做的是创建一个继承文件处理程序之一的类并覆盖on_modified更新文件时将调用的方法,如下所示

class CustomFileEventHandler(FileSystemHandler):
    def on_modified(self, event):
        file_name = event.src_path #get's the path of the modified file
        with open(file_name, "r") as infile, open("path/to/file.txt", "w") as result:
            #call your function which should return a string
            result.write(function output) #instead of print

无需附加“home/users/rmaestas”,因为 .src_path 将为您提供文件的完整路径。

使用覆盖的 FileSystemHandler,然后您需要设置 Observer,它将实际执行监视,这类似于看门狗文档中给出的示例

event_handler = CustomFileEventHandler()
observer = Observer()
observer.schedule(event_handler, "path/to/dir", recursive=False)
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()
于 2017-06-19T05:24:37.357 回答