Multithreading 无限循环是基于目录中文件更改进行处理的最佳解决方案吗
我正在编写一个工具,将文件添加到处理链中。我希望每10秒监视一个特定的已知目录,比较,并将结果发送到我已经存在的函数 我写了一篇短文:Multithreading 无限循环是基于目录中文件更改进行处理的最佳解决方案吗,multithreading,python-2.7,filesystemwatcher,Multithreading,Python 2.7,Filesystemwatcher,我正在编写一个工具,将文件添加到处理链中。我希望每10秒监视一个特定的已知目录,比较,并将结果发送到我已经存在的函数 我写了一篇短文: class Watchdog(Thread): def __init__(self, path): """ Constructor """ self.watch_folder = path self.verbose = True pass def run(self):
class Watchdog(Thread):
def __init__(self, path):
""" Constructor """
self.watch_folder = path
self.verbose = True
pass
def run(self):
"""
we check every 10s
"""
sleep_duration = 10
before = dict ([(f, None) for f in os.listdir (self.watch_folder)])
while True:
time.sleep(sleep_duration)
after = dict ([(f, None) for f in os.listdir (self.watch_folder)])
added_files = [f for f in after if not f in before]
removed_files = [f for f in before if not f in after]
if added_files and self.verbose:
print "Added: ", ", ".join (added_files)
if removed_files and self.verbose:
print "Removed: ", ", ".join (removed_files)
before = after
return added_files
我知道由于无休止的循环,我无法轻松返回数据。特别是因为该计划的其余部分是必不可少的
if __name__ == '__main__':
functionA()
do_smth()
# added_files is returned from the Thread and ideally changing.
if added_files >= n:
for file in added_files:
# happycode goes here, but how do I know about the change each time?
特别是:我可以简单地(不使用队列模型或任何非常复杂的东西)从线程返回吗?一旦线程可以报告更改,我就想启动处理函数(这是我的观察者)
我想知道是否有一种更简单的方法可以从无休止的循环中返回,从而使程序的其余部分保持必要性
希望这能有所帮助我目前正试图弄清楚回调函数是否有意义,以及如何使用它。