好吧,有更好的特定平台的方法来通知文件何时被创建。Gerrat在评论中提到了Windows的一种方法,pyinotify
可以用于Linux。这些特定平台的方法可以插入asyncio
,但是你最终会编写大量代码以使其以平台无关的方式工作,这可能并不值得只是检查单个文件的出现而已。如果需要更复杂的文件系统监视,那么追求这一点可能是值得的。例如,看起来pyinotify
可以调整其Notifier
类的子类,将其插入到asyncio
事件循环中(已经有适用于tornado
和asyncore
的类)。
对于您的简单用例,我认为轮询的无限循环方式很好,但是如果需要,您也可以使用事件循环安排回调函数:
def watch_for_file(file_path, interval=1, loop=None):
if not loop: loop = asyncio.get_event_loop()
if not os.path.exists(file_path):
print("{} not found yet.".format(file_path))
loop.call_later(interval, watch_for_file, file_path, interval, loop)
else:
print("{} found!".format(file_path))
loop.stop()
def main(argv=None):
cli_parser = make_cli_parser()
args = cli_parser.parse_args(argv)
loop = asyncio.get_event_loop()
loop.call_soon(watch_for_file, args.file_path)
loop.run_forever()
我不确定这比无限循环更优雅。
编辑:
只是为了好玩,我使用了pyinotify编写了一个解决方案:
import pyinotify
import asyncio
import argparse
import os.path
class AsyncioNotifier(pyinotify.Notifier):
"""
Notifier subclass that plugs into the asyncio event loop.
"""
def __init__(self, watch_manager, loop, callback=None,
default_proc_fun=None, read_freq=0, threshold=0, timeout=None):
self.loop = loop
self.handle_read_callback = callback
pyinotify.Notifier.__init__(self, watch_manager, default_proc_fun, read_freq,
threshold, timeout)
loop.add_reader(self._fd, self.handle_read)
def handle_read(self, *args, **kwargs):
self.read_events()
self.process_events()
if self.handle_read_callback is not None:
self.handle_read_callback(self)
class EventHandler(pyinotify.ProcessEvent):
def my_init(self, file=None, loop=None):
if not file:
raise ValueError("file keyword argument must be provided")
self.loop = loop if loop else asyncio.get_event_loop()
self.filename = file
def process_IN_CREATE(self, event):
print("Creating:", event.pathname)
if os.path.basename(event.pathname) == self.filename:
print("Found it!")
self.loop.stop()
def make_cli_parser():
cli_parser = argparse.ArgumentParser(description=__doc__)
cli_parser.add_argument('file_path')
return cli_parser
def main(argv=None):
cli_parser = make_cli_parser()
args = cli_parser.parse_args(argv)
loop = asyncio.get_event_loop()
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CREATE
dir_, filename = os.path.split(args.file_path)
if not dir_:
dir_ = "."
wm.add_watch(dir_, mask)
handler = EventHandler(file=filename, loop=loop)
notifier = pyinotify.AsyncioNotifier(wm, loop, default_proc_fun=handler)
loop.run_forever()
if __name__ == '__main__':
main()