无限循环是根据目录中的文件更改进行处理的最佳解决方案吗
Is an infinite loop the best solution to process based on file changes in a directory
我正在编写一个将文件添加到处理链的工具。我想每 10 秒监控一个特定的已知目录,进行比较,并将结果发送到我已经存在的函数中。
我写了一篇短文class:
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
我知道由于无限循环,我无法轻易 return 数据。特别是因为程序的其余部分是命令式的
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?
特别是:我可以简单地(不使用队列模型或任何极其复杂的东西)从线程 return 吗?一旦线程可以报告更改(所以这是我的观察者),我想开始处理功能。
我想知道是否有更简单的方法可以从无限循环中return,以便程序的其余部分可以保持命令式。
- 这是一篇关于您正在寻找的内容的好文章(幸运的是,在 python 中)
http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html
- 或者,我会在 python 中使用 'find -mtime n' linux 命令,如果这是用于 linux/linux,例如 OS
编辑:我知道 1 和 2,不要在无限循环中回答你的问题,而是替代方案。另外,
- http://linux.die.net/man/1/dnotify 也可能是替代方案
希望对您有所帮助
我正在编写一个将文件添加到处理链的工具。我想每 10 秒监控一个特定的已知目录,进行比较,并将结果发送到我已经存在的函数中。
我写了一篇短文class:
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
我知道由于无限循环,我无法轻易 return 数据。特别是因为程序的其余部分是命令式的
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?
特别是:我可以简单地(不使用队列模型或任何极其复杂的东西)从线程 return 吗?一旦线程可以报告更改(所以这是我的观察者),我想开始处理功能。
我想知道是否有更简单的方法可以从无限循环中return,以便程序的其余部分可以保持命令式。
- 这是一篇关于您正在寻找的内容的好文章(幸运的是,在 python 中)
http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html
- 或者,我会在 python 中使用 'find -mtime n' linux 命令,如果这是用于 linux/linux,例如 OS
编辑:我知道 1 和 2,不要在无限循环中回答你的问题,而是替代方案。另外,
- http://linux.die.net/man/1/dnotify 也可能是替代方案
希望对您有所帮助