Reputation: 107
Using watchdog, I want it to look for an updated file in some directory, in the event of that updated file it grabs the file name and runs a specific script with the file name and sends the output to a different directory as a txt file. When the text file appears in the new directory, somehow get the name of the file and set it as a variable for analysis.
EX:
First directory /path/to/first/dir/2017/04/27/nfcapd.20170427 <- New File (Notice, not a txt file)
Script is ran to obtain data in that file below by using above file name
nfdump - r nfcapd.20170427 > home/users/rmaestas/nfcapd.20170427.txt
File name is stored into a variable to be used with code
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...
Upvotes: 0
Views: 2663
Reputation: 79
What you need to do is to create a class which inherits one of the file handler's and override the on_modified
method which will be called when a file is updated, like so
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
There's no need to append 'home/users/rmaestas' since .src_path will give you the full path of the file.
With your overridden FileSystemHandler, you then need to set up the Observer which will actually do the monitoring which is similar to the example given in watchdog's documentation
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()
Upvotes: 3