Monitoring updating directory for image for GUI

Piet van Oostrum piet at vanoostrum.org
Thu Feb 7 18:11:47 CET 2013


ciscorucinski at gmail.com writes:

> Hello,
>
> I have been using Python for a few months now, so I am still learning a few things here and there.
>
> Basically I am creating a program that will stream musical notes into a program called Lilypond one-by-one and it will create the sheet music for that stream of music via OS command. Your understanding of Lilypond is not needed, but you need to know that for each new note that is streamed in "real-time", a PNG image file will be created for that stream of music up to that point...via Lilypond.
>
> What I am looking at doing is to monitor the directory where the image files are being created in real-time, and update the GUI (build with gtk.Builder and Glade) with the most recent image file. I have the program multithreaded and it appears that all of the images are being created sequentially; however, I need to make sure that an older image (an image with less notes displayed) is NOT going to be displayed over a newer image.
>
> The question I have is what do you see as the best way of going about this? 
>
> I have looked at creating a Stack from the python List, along with os.walk(). However, I am not sure if those are adequate with a directory that is actively adding new files. Also, how I imagined using the Stack with taking the next item off of the stack meant that older ones would be replacing new ones...and with a queue, it might be updating too slow; especially if the notes being streamed in are played fast. So I would like for the most recent image to be used and all others discarded.
>
I suppose you have two threads, one for producing the music by calling
Lilypond, and one for displaying the generated images. Because it is
multithreaded you should use a Queue from the module
Queue(Python2)/queue(Python3) to communicate between the threads.

Producing thread:
  send note to Lilypond
  wait until PNG file is generated (Lilypond completed)
  Q.put(filename)

Displaying thread:
  while True:
    fn = Q.get() # this will block until a filename is available
    # now check if there is more in the queue
    while True:
      try:
        fn = Q.get_nowait
        # here we got a newer one
      except Empty:
        break # stop the inner loop
    display the image in fn.

In this way you always display the most recent one.
You can make it more sophisticated by removing files that have been
displayed and files that you skip.

-- 
Piet van Oostrum <piet at vanoostrum.org>
WWW: http://pietvanoostrum.com/
PGP key: [8DAE142BE17999C4]



More information about the Python-list mailing list