Pass a Queue to watchdog thread in python2019 Community Moderator ElectionCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?“implements Runnable” vs “extends Thread” in JavaHow do I pass a variable by reference?How to use threading in Python?Does Python have a string 'contains' substring method?

PTIJ: Should I kill my computer after installing software?

What was the Kree's motivation in Captain Marvel?

Looking for word that is not atheist or agnostic,

What is the cause of the Apocalypse in The Umbrella Academy?

Is it necessary to separate DC power cables and data cables?

Was it really inappropriate to write a pull request for the company I interviewed with?

What are some noteworthy "mic-drop" moments in math?

How do I express some one as a black person?

cat shows nothing

Are all players supposed to be able to see each others' character sheets?

How are showroom/display vehicles prepared?

Coax or bifilar choke

What was the implant device Captain Marvel was using?

Do f-stop and exposure time perfectly cancel?

Latex does not go to next line

In the late 1940’s to early 1950’s what technology was available that could melt a LOT of ice?

Can you reject a postdoc offer after the PI has paid a large sum for flights/accommodation for your visit?

Bash script should only kill those instances of another script's that it has launched

Is "history" a male-biased word ("his+story")?

Examples of a statistic that is not independent of sample's distribution?

Was Luke Skywalker the leader of the Rebel forces on Hoth?

How does NOW work?

Can one live in the U.S. and not use a credit card?

Do I really need to have a scientific explanation for my premise?



Pass a Queue to watchdog thread in python



2019 Community Moderator ElectionCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?“implements Runnable” vs “extends Thread” in JavaHow do I pass a variable by reference?How to use threading in Python?Does Python have a string 'contains' substring method?










0















I have a class Indexer which is instantiated from the main thread, the instance of this class is stored in a variable, say, indexer. watchdog.observers.Observer() watches directories for changes and these happen in another thread. I tried passing this indexer variable from main thread through my handler Vigilante which was passed to ob.schedule(Vigilante(indexer)) alongside some other variables from main thread. I can't access the indexer variable in the Vigilante class, because of being in different threads. I know I could use a Queue but I don't know how I'd pass the Queue to watchdog's thread.



Here is the code from main thread:



if watch:
import watchdog.observers
from .utils import vigilante
class callbacks:
def __init__(self):
pass
@staticmethod
def build(filename, response):
return _build(filename, response)
@staticmethod
def renderer(src, mode):
return render(src, mode)
handler = vigilante.Vigilante(_filter, ignore, Indexer, callbacks, Mode)
path_to_watch = os.path.normpath(os.path.join(workspace, '..'))
ob = watchdog.observers.Observer()
ob.schedule(handler, path=path_to_watch, recursive=True)
ob.start()
import time
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
ob.stop()
Indexer.close()
ob.join()


The Indexer class is meant to write to a database from another part of the code where the Indexer was instantiated.



Here is the code from Vigilante class running in watchdog's thread:



class Vigilante(PatternMatchingEventHandler):
"""Helps to watch files, directories for changes"""
def __init__(self, pattern, ignore, indexer, callback, mode):
pattern.append("*.yml")
self.Callback = callback
self.Mode = mode
self.Indexer = indexer
super(Vigilante, self).__init__(patterns=pattern, ignore_directories=ignore)

def vigil(self, event):
print(event.src_path, 'modified')
IndexReader = self.Indexer.get_index_on(event.src_path)
dep = IndexReader.read_index()
print(dep.next(), 'dependency')
feedout = self.Callback.build(
os.path.basename(event.src_path)
,self.Callback.renderer(event.src_path, self.Mode.FILE_MODE)
)

def on_modified(self, event):
self.vigil(event)

def on_created(self, event):
self.vigil(event)


All I need is a way to pass those variables from the main thread to watchdog's thread, through the Vigilante class










share|improve this question


























    0















    I have a class Indexer which is instantiated from the main thread, the instance of this class is stored in a variable, say, indexer. watchdog.observers.Observer() watches directories for changes and these happen in another thread. I tried passing this indexer variable from main thread through my handler Vigilante which was passed to ob.schedule(Vigilante(indexer)) alongside some other variables from main thread. I can't access the indexer variable in the Vigilante class, because of being in different threads. I know I could use a Queue but I don't know how I'd pass the Queue to watchdog's thread.



    Here is the code from main thread:



    if watch:
    import watchdog.observers
    from .utils import vigilante
    class callbacks:
    def __init__(self):
    pass
    @staticmethod
    def build(filename, response):
    return _build(filename, response)
    @staticmethod
    def renderer(src, mode):
    return render(src, mode)
    handler = vigilante.Vigilante(_filter, ignore, Indexer, callbacks, Mode)
    path_to_watch = os.path.normpath(os.path.join(workspace, '..'))
    ob = watchdog.observers.Observer()
    ob.schedule(handler, path=path_to_watch, recursive=True)
    ob.start()
    import time
    try:
    while True:
    time.sleep(1)
    except KeyboardInterrupt:
    ob.stop()
    Indexer.close()
    ob.join()


    The Indexer class is meant to write to a database from another part of the code where the Indexer was instantiated.



    Here is the code from Vigilante class running in watchdog's thread:



    class Vigilante(PatternMatchingEventHandler):
    """Helps to watch files, directories for changes"""
    def __init__(self, pattern, ignore, indexer, callback, mode):
    pattern.append("*.yml")
    self.Callback = callback
    self.Mode = mode
    self.Indexer = indexer
    super(Vigilante, self).__init__(patterns=pattern, ignore_directories=ignore)

    def vigil(self, event):
    print(event.src_path, 'modified')
    IndexReader = self.Indexer.get_index_on(event.src_path)
    dep = IndexReader.read_index()
    print(dep.next(), 'dependency')
    feedout = self.Callback.build(
    os.path.basename(event.src_path)
    ,self.Callback.renderer(event.src_path, self.Mode.FILE_MODE)
    )

    def on_modified(self, event):
    self.vigil(event)

    def on_created(self, event):
    self.vigil(event)


    All I need is a way to pass those variables from the main thread to watchdog's thread, through the Vigilante class










    share|improve this question
























      0












      0








      0








      I have a class Indexer which is instantiated from the main thread, the instance of this class is stored in a variable, say, indexer. watchdog.observers.Observer() watches directories for changes and these happen in another thread. I tried passing this indexer variable from main thread through my handler Vigilante which was passed to ob.schedule(Vigilante(indexer)) alongside some other variables from main thread. I can't access the indexer variable in the Vigilante class, because of being in different threads. I know I could use a Queue but I don't know how I'd pass the Queue to watchdog's thread.



      Here is the code from main thread:



      if watch:
      import watchdog.observers
      from .utils import vigilante
      class callbacks:
      def __init__(self):
      pass
      @staticmethod
      def build(filename, response):
      return _build(filename, response)
      @staticmethod
      def renderer(src, mode):
      return render(src, mode)
      handler = vigilante.Vigilante(_filter, ignore, Indexer, callbacks, Mode)
      path_to_watch = os.path.normpath(os.path.join(workspace, '..'))
      ob = watchdog.observers.Observer()
      ob.schedule(handler, path=path_to_watch, recursive=True)
      ob.start()
      import time
      try:
      while True:
      time.sleep(1)
      except KeyboardInterrupt:
      ob.stop()
      Indexer.close()
      ob.join()


      The Indexer class is meant to write to a database from another part of the code where the Indexer was instantiated.



      Here is the code from Vigilante class running in watchdog's thread:



      class Vigilante(PatternMatchingEventHandler):
      """Helps to watch files, directories for changes"""
      def __init__(self, pattern, ignore, indexer, callback, mode):
      pattern.append("*.yml")
      self.Callback = callback
      self.Mode = mode
      self.Indexer = indexer
      super(Vigilante, self).__init__(patterns=pattern, ignore_directories=ignore)

      def vigil(self, event):
      print(event.src_path, 'modified')
      IndexReader = self.Indexer.get_index_on(event.src_path)
      dep = IndexReader.read_index()
      print(dep.next(), 'dependency')
      feedout = self.Callback.build(
      os.path.basename(event.src_path)
      ,self.Callback.renderer(event.src_path, self.Mode.FILE_MODE)
      )

      def on_modified(self, event):
      self.vigil(event)

      def on_created(self, event):
      self.vigil(event)


      All I need is a way to pass those variables from the main thread to watchdog's thread, through the Vigilante class










      share|improve this question














      I have a class Indexer which is instantiated from the main thread, the instance of this class is stored in a variable, say, indexer. watchdog.observers.Observer() watches directories for changes and these happen in another thread. I tried passing this indexer variable from main thread through my handler Vigilante which was passed to ob.schedule(Vigilante(indexer)) alongside some other variables from main thread. I can't access the indexer variable in the Vigilante class, because of being in different threads. I know I could use a Queue but I don't know how I'd pass the Queue to watchdog's thread.



      Here is the code from main thread:



      if watch:
      import watchdog.observers
      from .utils import vigilante
      class callbacks:
      def __init__(self):
      pass
      @staticmethod
      def build(filename, response):
      return _build(filename, response)
      @staticmethod
      def renderer(src, mode):
      return render(src, mode)
      handler = vigilante.Vigilante(_filter, ignore, Indexer, callbacks, Mode)
      path_to_watch = os.path.normpath(os.path.join(workspace, '..'))
      ob = watchdog.observers.Observer()
      ob.schedule(handler, path=path_to_watch, recursive=True)
      ob.start()
      import time
      try:
      while True:
      time.sleep(1)
      except KeyboardInterrupt:
      ob.stop()
      Indexer.close()
      ob.join()


      The Indexer class is meant to write to a database from another part of the code where the Indexer was instantiated.



      Here is the code from Vigilante class running in watchdog's thread:



      class Vigilante(PatternMatchingEventHandler):
      """Helps to watch files, directories for changes"""
      def __init__(self, pattern, ignore, indexer, callback, mode):
      pattern.append("*.yml")
      self.Callback = callback
      self.Mode = mode
      self.Indexer = indexer
      super(Vigilante, self).__init__(patterns=pattern, ignore_directories=ignore)

      def vigil(self, event):
      print(event.src_path, 'modified')
      IndexReader = self.Indexer.get_index_on(event.src_path)
      dep = IndexReader.read_index()
      print(dep.next(), 'dependency')
      feedout = self.Callback.build(
      os.path.basename(event.src_path)
      ,self.Callback.renderer(event.src_path, self.Mode.FILE_MODE)
      )

      def on_modified(self, event):
      self.vigil(event)

      def on_created(self, event):
      self.vigil(event)


      All I need is a way to pass those variables from the main thread to watchdog's thread, through the Vigilante class







      python multithreading queue watchdog






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 6 at 15:14









      CalebPitanCalebPitan

      14




      14






















          2 Answers
          2






          active

          oldest

          votes


















          0














          I finally found a way to do it without crossing threads too much as before, with an idea derived from @EvertW 's answer. I passed a Queue from main thread to the Vigilante class which was in another thread, so every modified file would be put in the Queue and then, from the main thread, I got the file modified from the queue, read from the Indexer database, and every other task which the Vigilante.vigil method needed to perform was moved to the main thread since those tasks depends on the modified file and what is read from the Indexer database.



          This error disappeared:




          SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 9788 and this is thread id 4288.




          Here is a snippet from what I did:



          ....
          q = Queue.LifoQueue(10)
          handler = vigilante.Vigilante(q, _filter, ignore)
          path_to_watch = os.path.normpath(os.path.join(workspace, '..'))
          ob = watchdog.observers.Observer()
          ob.schedule(handler, path=path_to_watch, recursive=True)
          ob.start()
          import time
          try:
          while True:
          if not q.empty():
          modified = q.get()
          IndexReader = Indexer.get_index_on(modified)
          deps = IndexReader.read_index()
          print(deps.next(), 'dependency')
          # TODO
          else:
          print('q is empty')
          time.sleep(1)
          except KeyboardInterrupt:
          ob.stop()
          Indexer.close()
          ob.join()


          Vigilante class:



          class Vigilante(PatternMatchingEventHandler):
          """Helps to watch files, directories for changes"""
          def __init__(self, q, pattern, ignore):
          self.q = q
          super(Vigilante, self).__init__(
          patterns=pattern,
          ignore_patterns=ignore,
          ignore_directories=True
          )

          def vigil(self, event):
          print(event.src_path, 'modified')
          self.q.put(event.src_path)

          def on_modified(self, event):
          self.vigil(event)

          def on_created(self, event):
          self.vigil(event)
          ....


          PS: A word of advice : my word of advice to whoever comes across this kind of problem with threading in watchdog is; "Don't trust the watchdog's thread to do tasks on modified files, just get the modified files out and do whatever you like with them, except the task is a simple one."






          share|improve this answer
































            0














            You could try the Observer pattern (no pun intended), i.e. let the Observer class have a list of listeners that it will inform of any changes it sees. Then let the indexer announce its interest to the Observer.



            In my example, the Observer expects subscribers to be callables that receive the changes. Then you can do:



            from queue import Queue
            class Observable:
            def __init__(self):
            self.listeners = []
            def subscribe(listener):
            self.listeners.append(listener)
            def onNotify(change):
            for listener in self.listeners:
            listener(change)

            class Indexer(Thread):
            def __init__(self, observer):
            Thread.__init__(self)
            self.q = Queue()
            observer.subscribe(self.q.put)
            def run(self):
            while True:
            change = self.q.get()


            Because the standard Queue is completely thread-safe, this will work fine.






            share|improve this answer
























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55026383%2fpass-a-queue-to-watchdog-thread-in-python%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              I finally found a way to do it without crossing threads too much as before, with an idea derived from @EvertW 's answer. I passed a Queue from main thread to the Vigilante class which was in another thread, so every modified file would be put in the Queue and then, from the main thread, I got the file modified from the queue, read from the Indexer database, and every other task which the Vigilante.vigil method needed to perform was moved to the main thread since those tasks depends on the modified file and what is read from the Indexer database.



              This error disappeared:




              SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 9788 and this is thread id 4288.




              Here is a snippet from what I did:



              ....
              q = Queue.LifoQueue(10)
              handler = vigilante.Vigilante(q, _filter, ignore)
              path_to_watch = os.path.normpath(os.path.join(workspace, '..'))
              ob = watchdog.observers.Observer()
              ob.schedule(handler, path=path_to_watch, recursive=True)
              ob.start()
              import time
              try:
              while True:
              if not q.empty():
              modified = q.get()
              IndexReader = Indexer.get_index_on(modified)
              deps = IndexReader.read_index()
              print(deps.next(), 'dependency')
              # TODO
              else:
              print('q is empty')
              time.sleep(1)
              except KeyboardInterrupt:
              ob.stop()
              Indexer.close()
              ob.join()


              Vigilante class:



              class Vigilante(PatternMatchingEventHandler):
              """Helps to watch files, directories for changes"""
              def __init__(self, q, pattern, ignore):
              self.q = q
              super(Vigilante, self).__init__(
              patterns=pattern,
              ignore_patterns=ignore,
              ignore_directories=True
              )

              def vigil(self, event):
              print(event.src_path, 'modified')
              self.q.put(event.src_path)

              def on_modified(self, event):
              self.vigil(event)

              def on_created(self, event):
              self.vigil(event)
              ....


              PS: A word of advice : my word of advice to whoever comes across this kind of problem with threading in watchdog is; "Don't trust the watchdog's thread to do tasks on modified files, just get the modified files out and do whatever you like with them, except the task is a simple one."






              share|improve this answer





























                0














                I finally found a way to do it without crossing threads too much as before, with an idea derived from @EvertW 's answer. I passed a Queue from main thread to the Vigilante class which was in another thread, so every modified file would be put in the Queue and then, from the main thread, I got the file modified from the queue, read from the Indexer database, and every other task which the Vigilante.vigil method needed to perform was moved to the main thread since those tasks depends on the modified file and what is read from the Indexer database.



                This error disappeared:




                SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 9788 and this is thread id 4288.




                Here is a snippet from what I did:



                ....
                q = Queue.LifoQueue(10)
                handler = vigilante.Vigilante(q, _filter, ignore)
                path_to_watch = os.path.normpath(os.path.join(workspace, '..'))
                ob = watchdog.observers.Observer()
                ob.schedule(handler, path=path_to_watch, recursive=True)
                ob.start()
                import time
                try:
                while True:
                if not q.empty():
                modified = q.get()
                IndexReader = Indexer.get_index_on(modified)
                deps = IndexReader.read_index()
                print(deps.next(), 'dependency')
                # TODO
                else:
                print('q is empty')
                time.sleep(1)
                except KeyboardInterrupt:
                ob.stop()
                Indexer.close()
                ob.join()


                Vigilante class:



                class Vigilante(PatternMatchingEventHandler):
                """Helps to watch files, directories for changes"""
                def __init__(self, q, pattern, ignore):
                self.q = q
                super(Vigilante, self).__init__(
                patterns=pattern,
                ignore_patterns=ignore,
                ignore_directories=True
                )

                def vigil(self, event):
                print(event.src_path, 'modified')
                self.q.put(event.src_path)

                def on_modified(self, event):
                self.vigil(event)

                def on_created(self, event):
                self.vigil(event)
                ....


                PS: A word of advice : my word of advice to whoever comes across this kind of problem with threading in watchdog is; "Don't trust the watchdog's thread to do tasks on modified files, just get the modified files out and do whatever you like with them, except the task is a simple one."






                share|improve this answer



























                  0












                  0








                  0







                  I finally found a way to do it without crossing threads too much as before, with an idea derived from @EvertW 's answer. I passed a Queue from main thread to the Vigilante class which was in another thread, so every modified file would be put in the Queue and then, from the main thread, I got the file modified from the queue, read from the Indexer database, and every other task which the Vigilante.vigil method needed to perform was moved to the main thread since those tasks depends on the modified file and what is read from the Indexer database.



                  This error disappeared:




                  SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 9788 and this is thread id 4288.




                  Here is a snippet from what I did:



                  ....
                  q = Queue.LifoQueue(10)
                  handler = vigilante.Vigilante(q, _filter, ignore)
                  path_to_watch = os.path.normpath(os.path.join(workspace, '..'))
                  ob = watchdog.observers.Observer()
                  ob.schedule(handler, path=path_to_watch, recursive=True)
                  ob.start()
                  import time
                  try:
                  while True:
                  if not q.empty():
                  modified = q.get()
                  IndexReader = Indexer.get_index_on(modified)
                  deps = IndexReader.read_index()
                  print(deps.next(), 'dependency')
                  # TODO
                  else:
                  print('q is empty')
                  time.sleep(1)
                  except KeyboardInterrupt:
                  ob.stop()
                  Indexer.close()
                  ob.join()


                  Vigilante class:



                  class Vigilante(PatternMatchingEventHandler):
                  """Helps to watch files, directories for changes"""
                  def __init__(self, q, pattern, ignore):
                  self.q = q
                  super(Vigilante, self).__init__(
                  patterns=pattern,
                  ignore_patterns=ignore,
                  ignore_directories=True
                  )

                  def vigil(self, event):
                  print(event.src_path, 'modified')
                  self.q.put(event.src_path)

                  def on_modified(self, event):
                  self.vigil(event)

                  def on_created(self, event):
                  self.vigil(event)
                  ....


                  PS: A word of advice : my word of advice to whoever comes across this kind of problem with threading in watchdog is; "Don't trust the watchdog's thread to do tasks on modified files, just get the modified files out and do whatever you like with them, except the task is a simple one."






                  share|improve this answer















                  I finally found a way to do it without crossing threads too much as before, with an idea derived from @EvertW 's answer. I passed a Queue from main thread to the Vigilante class which was in another thread, so every modified file would be put in the Queue and then, from the main thread, I got the file modified from the queue, read from the Indexer database, and every other task which the Vigilante.vigil method needed to perform was moved to the main thread since those tasks depends on the modified file and what is read from the Indexer database.



                  This error disappeared:




                  SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 9788 and this is thread id 4288.




                  Here is a snippet from what I did:



                  ....
                  q = Queue.LifoQueue(10)
                  handler = vigilante.Vigilante(q, _filter, ignore)
                  path_to_watch = os.path.normpath(os.path.join(workspace, '..'))
                  ob = watchdog.observers.Observer()
                  ob.schedule(handler, path=path_to_watch, recursive=True)
                  ob.start()
                  import time
                  try:
                  while True:
                  if not q.empty():
                  modified = q.get()
                  IndexReader = Indexer.get_index_on(modified)
                  deps = IndexReader.read_index()
                  print(deps.next(), 'dependency')
                  # TODO
                  else:
                  print('q is empty')
                  time.sleep(1)
                  except KeyboardInterrupt:
                  ob.stop()
                  Indexer.close()
                  ob.join()


                  Vigilante class:



                  class Vigilante(PatternMatchingEventHandler):
                  """Helps to watch files, directories for changes"""
                  def __init__(self, q, pattern, ignore):
                  self.q = q
                  super(Vigilante, self).__init__(
                  patterns=pattern,
                  ignore_patterns=ignore,
                  ignore_directories=True
                  )

                  def vigil(self, event):
                  print(event.src_path, 'modified')
                  self.q.put(event.src_path)

                  def on_modified(self, event):
                  self.vigil(event)

                  def on_created(self, event):
                  self.vigil(event)
                  ....


                  PS: A word of advice : my word of advice to whoever comes across this kind of problem with threading in watchdog is; "Don't trust the watchdog's thread to do tasks on modified files, just get the modified files out and do whatever you like with them, except the task is a simple one."







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 2 days ago









                  marc_s

                  581k13011201267




                  581k13011201267










                  answered Mar 7 at 15:33









                  CalebPitanCalebPitan

                  14




                  14























                      0














                      You could try the Observer pattern (no pun intended), i.e. let the Observer class have a list of listeners that it will inform of any changes it sees. Then let the indexer announce its interest to the Observer.



                      In my example, the Observer expects subscribers to be callables that receive the changes. Then you can do:



                      from queue import Queue
                      class Observable:
                      def __init__(self):
                      self.listeners = []
                      def subscribe(listener):
                      self.listeners.append(listener)
                      def onNotify(change):
                      for listener in self.listeners:
                      listener(change)

                      class Indexer(Thread):
                      def __init__(self, observer):
                      Thread.__init__(self)
                      self.q = Queue()
                      observer.subscribe(self.q.put)
                      def run(self):
                      while True:
                      change = self.q.get()


                      Because the standard Queue is completely thread-safe, this will work fine.






                      share|improve this answer





























                        0














                        You could try the Observer pattern (no pun intended), i.e. let the Observer class have a list of listeners that it will inform of any changes it sees. Then let the indexer announce its interest to the Observer.



                        In my example, the Observer expects subscribers to be callables that receive the changes. Then you can do:



                        from queue import Queue
                        class Observable:
                        def __init__(self):
                        self.listeners = []
                        def subscribe(listener):
                        self.listeners.append(listener)
                        def onNotify(change):
                        for listener in self.listeners:
                        listener(change)

                        class Indexer(Thread):
                        def __init__(self, observer):
                        Thread.__init__(self)
                        self.q = Queue()
                        observer.subscribe(self.q.put)
                        def run(self):
                        while True:
                        change = self.q.get()


                        Because the standard Queue is completely thread-safe, this will work fine.






                        share|improve this answer



























                          0












                          0








                          0







                          You could try the Observer pattern (no pun intended), i.e. let the Observer class have a list of listeners that it will inform of any changes it sees. Then let the indexer announce its interest to the Observer.



                          In my example, the Observer expects subscribers to be callables that receive the changes. Then you can do:



                          from queue import Queue
                          class Observable:
                          def __init__(self):
                          self.listeners = []
                          def subscribe(listener):
                          self.listeners.append(listener)
                          def onNotify(change):
                          for listener in self.listeners:
                          listener(change)

                          class Indexer(Thread):
                          def __init__(self, observer):
                          Thread.__init__(self)
                          self.q = Queue()
                          observer.subscribe(self.q.put)
                          def run(self):
                          while True:
                          change = self.q.get()


                          Because the standard Queue is completely thread-safe, this will work fine.






                          share|improve this answer















                          You could try the Observer pattern (no pun intended), i.e. let the Observer class have a list of listeners that it will inform of any changes it sees. Then let the indexer announce its interest to the Observer.



                          In my example, the Observer expects subscribers to be callables that receive the changes. Then you can do:



                          from queue import Queue
                          class Observable:
                          def __init__(self):
                          self.listeners = []
                          def subscribe(listener):
                          self.listeners.append(listener)
                          def onNotify(change):
                          for listener in self.listeners:
                          listener(change)

                          class Indexer(Thread):
                          def __init__(self, observer):
                          Thread.__init__(self)
                          self.q = Queue()
                          observer.subscribe(self.q.put)
                          def run(self):
                          while True:
                          change = self.q.get()


                          Because the standard Queue is completely thread-safe, this will work fine.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited 2 days ago

























                          answered Mar 6 at 16:08









                          EvertWEvertW

                          661516




                          661516



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55026383%2fpass-a-queue-to-watchdog-thread-in-python%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

                              Алба-Юлія

                              Захаров Федір Захарович