Gateway Script to monitor directory for new files

I wanted to update with a solution for an obstacle I ran into when trying to open files identified by this watcher. I saw the following regardless of using WatchService.take() or WatchService.poll().

  • File paths are reliably collected and always immediately verifiable with os.path(path) returning True
  • Upon immediate inspection after a WatchService notification, some files return False from Files.isReadable(path) and will throw IOError[2] No such file if opened
  • After a short delay (i.e. 3 seconds) these files can be opened

I used this check to ensure every new file is eventually opened:

import os
from java.nio.file import Files, Paths
from time import sleep

pathCheck = os.path.isfile(path)
readCheck = Files.isReadable(Paths.get(path))
target = None

if pathCheck & readCheck:
	target = open(path, 'rb')
else:
	for i in range(5):
		sleep(3)
		try:
			target = open(path, 'rb')
			break
		except IOError, e:
			if e.errno == 2:
				pass
			else:
				raise
2 Likes