python watchfiles类-watch功能

文章介绍了如何使用Python的watchfiles库实现对指定目录的文件变化进行监控,并通过封装成类的方式提供停止监控和迭代处理文件更新的功能。示例展示了如何创建Test类,以及其run方法和相关事件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

watchfiles类-watch功能:监控指定目录文件变化,并进行通知。

from watchfiles import watch
for changes in watch('./'):
    print(changes)

打印当前目录更新的文件。

import threading
from watchfiles import watch
class Test:
    def __init__(self,path):
        self.event = threading.Event()
        self.watcher = watch(path,stop_event=self.event,yield_on_timeout=True)
    
    def run(self):
        print("--start--")
        for path in self:
            print("path:",path)
            if path:
                print("stoping")
                self.stop()
        print("--end--")

    def __iter__(self):
        return self

    def __next__(self):
        return self.get()
    
    def get(self):
        return next(self.watcher)
    
    def stop(self):
        print("--stop--")
        self.event.set()

Test("./").run()

以上为 封装成class的调用方式。

(venv) root@dns-web:/opt/dash-fastapi-admin/dash-fastapi-backend# uvicorn server:app --host 0.0.0.0 --port 8000 --reload INFO: Will watch for changes in these directories: ['/opt/dash-fastapi-admin/dash-fastapi-backend'] INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit) INFO: Started reloader process [439281] using WatchFiles Process SpawnProcess-1: Traceback (most recent call last): File "/usr/lib/python3.11/multiprocessing/process.py", line 314, in _bootstrap self.run() File "/usr/lib/python3.11/multiprocessing/process.py", line 108, in run self._target(*self._args, **self._kwargs) File "/opt/dash-fastapi-admin/venv/lib/python3.11/site-packages/uvicorn/_subprocess.py", line 80, in subprocess_started target(sockets=sockets) File "/opt/dash-fastapi-admin/venv/lib/python3.11/site-packages/uvicorn/server.py", line 67, in run return asyncio.run(self.serve(sockets=sockets)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/asyncio/runners.py", line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/asyncio/runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "uvloop/loop.pyx", line 1518, in uvloop.loop.Loop.run_until_complete File "/opt/dash-fastapi-admin/venv/lib/python3.11/site-packages/uvicorn/server.py", line 71, in serve await self._serve(sockets) File "/opt/dash-fastapi-admin/venv/lib/python3.11/site-packages/uvicorn/server.py", line 78, in _serve config.load() File "/opt/dash-fastapi-admin/venv/lib/python3.11/site-packages/uvicorn/config.py", line 436, in load self.loaded_app = import_from_string(self.app) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/dash-fastapi-admin/venv/lib/python3.11/site-packages/uvicorn/importer.py", line 19, in import_from_string module = importlib.import_module(module_str) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/opt/dash-fastapi-admin/dash-fastapi-backend/server.py", line 3, in <module> from config.env import AppConfig File "/opt/dash-fastapi-admin/dash-fastapi-backend/config/env.py", line 55, in <module> class RedisSettings(BaseSettings): File "/opt/dash-fastapi-admin/venv/lib/python3.11/site-packages/pydantic/_internal/_model_construction.py", line 112, in __new__ private_attributes = inspect_namespace( ^^^^^^^^^^^^^^^^^^ File "/opt/dash-fastapi-admin/venv/lib/python3.11/site-packages/pydantic/_internal/_model_construction.py", line 459, in inspect_namespace raise PydanticUserError( pydantic.errors.PydanticUserError: A non-annotated attribute was detected: `CELERY_BROKER_URL = 'redis://:[email protected]:6379/0'`. All model fields require a type annotation; if `CELERY_BROKER_URL` is not meant to be a field, you may be able to resolve this error by annotating it as a `ClassVar` or updating `model_config['ignored_types']`. For further information visit https://errors.pydantic.dev/2.11/u/model-field-missing-annotation 出什么错
最新发布
07-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值