13

I am trying to create a simple app in which

  1. an image is pushed in a directory (by an outside process)

  2. Python watchdog triggers and the image is processed by a function and results are displayed in a window

The job is continuously running and the processing function is triggered as the image comes into the directory. The plot window for results should just be updated with new results instead of window closing and then re-plotting.

The code below does not display the results. The plot window remains blank and then crashes. If something other than matplotlib can do this job easily then that would be fine as well.

# plt is matplotlib.pyplot

def process_and_plot(test_file):
    y, x = getresults(test_file) # function which returns results on image file

    y_pos = range(len(y))
    plt.figure(num=1,figsize=(20,10))
    plt.bar(y_pos, y, align='center')
    plt.xticks(y_pos, x)
    plt.show()

# to trigger the proess_and_plt function when a new file comes in directory 

class ExampleHandler(FileSystemEventHandler):
    def on_created(self, event): 
        print event.src_path
        process_and_plot(event.src_path)

event_handler = ExampleHandler() 
observer.schedule(event_handler, path='path/to/directory')
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()

user262540
  • 391
  • 1
  • 3
  • 6

1 Answers1

2

The only thing I needed to do to get your code to work was replace plt.show() with plt.pause(.001), which is non-blocking and updates and displays the figure before pausing (see docs).

The best related answer on SO seems this. There are some suggestions to use plt.show(False) or plt.ion() to make plt.show() non-blocking; neither worked for me with Matplotlib 2.2.4.

Here the complete code since the code in the question left out a few lines:

import matplotlib.pyplot as plt, time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

def process_and_plot(test_file):
    #y, x = getresults(test_file) # function which returns results on image file
    y, x = [2, 4, 3], [0, 1, 2]

    y_pos = range(len(y))
    plt.figure(num=1,figsize=(20,10))
    plt.title(test_file)
    plt.bar(y_pos, y, align='center')
    plt.xticks(y_pos, x)
    plt.pause(.001)

# to trigger the proess_and_plt function when a new file comes in directory 

class ExampleHandler(FileSystemEventHandler):
    def on_created(self, event):
        print event.src_path
        process_and_plot(event.src_path)

event_handler = ExampleHandler()
observer = Observer()
observer.schedule(event_handler, path='/path/to/directory')
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()
Ulrich Stern
  • 8,926
  • 4
  • 46
  • 68