我在 Amazon Linux EC2 实例中有一个目录结构。我希望有一个 Python 脚本异步监视此目录(和所有子目录)以创建文件。
我决定在子进程中运行 inotifywait 并将输出传递给异步任务进行处理。我运行子进程并在其自己的线程中监视输出,并将标准输出传递给asyncio.Queue()
using put_nowait()
,由在主线程上运行的 asyncio 任务监视。
import asyncio
import subprocess
import threading
def watch_dir(dir_to_watch: str, output_queue: asyncio.Queue):
inotify_cmd = f'sudo inotifywait -e create -m -r {dir_to_watch}'
proc = subprocess.Popen(inotify_cmd,
stdout=subprocess.PIPE,
shell=True)
while True:
line = proc.stdout.readline().rstrip()
if not line:
break
output_queue.put_nowait(line)
async def process_lines(input_queue: asyncio.Queue):
while True:
line = await input_queue.get()
# do stuff with line
if __name__ == '__main__':
q = asyncio.Queue()
dir_watch_thread = threading.Thread(target=watch_dir, args=(_dir_to_watch, q))
dir_watch_thread.start()
asyncio.run(process_lines(q))
有没有更好、性能/资源效率更高的方法来做到这一点?这甚至是安全的用法asyncio.Queue()
吗?我已经阅读了有关janus的内容,它将自己描述为通过同步和异步上下文之间的队列传递数据的安全方式。我是否需要使用这样的数据结构(为什么)?如果不需要,我不想包含额外的依赖项。