Find Any Addition / removal of file in directory in parallel

Asked by Chetan

hello
i would like to have a listener which highlights me if any file is added / removed in a directory

Usage:
i have an application that crashes and creates a dump file in a folder. which get uploaded and then removed from the folder

i want to check when sikuli script intentionally crashes my application then if the crash file is created in the folder and then removed

any pointers would be appreciated

Question information

Language:
English Edit question
Status:
Solved
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Solved by:
RaiMan
Solved:
Last query:
Last reply:
Revision history for this message
RaiMan (raimund-hocke) said :
#1

Since we are on Jython/Java, you can try with:

https://www.baeldung.com/java-nio2-watchservice

The are solutions for Python (e.g. watchdog), but I doubt that the packages are Jython/Java compatible (Python code only), since with a fast check I suppose they are using C-based stuff/libraries internally.
But I did not try - at least watchdog looks promising in terms of features.

Revision history for this message
Chetan (cshamdas) said :
#2

ok. however our scripts are in python. would it work inside our py scripts?

Revision history for this message
RaiMan (raimund-hocke) said :
#3

Java is useable from inside Jython scripts.

I will give you a sample later.

meanwhile: https://www.jython.org/jython-old-sites/archive/21/docs/usejava.html

Revision history for this message
Best RaiMan (raimund-hocke) said :
#4

based on the baeldung example:

import java.nio.file.FileSystems as FileSystems
import java.nio.file.Paths as Paths
import java.nio.file.StandardWatchEventKinds as WatchKinds

watchService = FileSystems.getDefault().newWatchService();
path = Paths.get("<some existing folder>")
path.register(watchService, WatchKinds.ENTRY_CREATE)

print "Starting watch"
while True:
    key = watchService.take()
    if not key:
        print "... stopping"
        break
    print "... checking"
    for event in key.pollEvents():
        print event.context()
    key.reset();
    exit()

when started, it waits for a new file to show up in the given folder, prints and exits.

Since watchService.take is blocking, it must run in a subprocess.

Revision history for this message
Chetan (cshamdas) said :
#5

Thanks a ton raiman

Revision history for this message
Chetan (cshamdas) said :
#6

Thanks RaiMan, that solved my question.