How to combine 2 threads in Asyncio?

37 Views Asked by At

There are 2 scripts: 1- Observer - receives a file change event and reads the file itself.

Example: In the directory 'C:\ForTest ' there is a file text.txt If we write something to a file text.txt and if we save it, then the console should output: the path to the file that has been changed, and the text from the file.

2- Standard bot on AIOGram. How to combine 2 threads so that when the bot is running, the Observer script works?

I tried it like this, by adding a task, until it was fully implemented, but the bot works, and the files are not readable:

import asyncio
import logging
from datetime import datetime

from aiogram import Bot, Dispatcher, types, html, F
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.filters import Command, CommandObject
from aiogram.types import FSInputFile, URLInputFile, BufferedInputFile
from aiogram.utils.markdown import hide_link

from config import config
import Handlers
from sqlFile import db, sql, create_sql

##########
import time

from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

##########

bot = Bot(token=config['token'], parse_mode="HTML")
storage: MemoryStorage = MemoryStorage()
dp = Dispatcher(storage=storage)
logging.basicConfig(level=logging.INFO)
create_sql()
loop = asyncio.get_event_loop()


##########
class MyHandler(PatternMatchingEventHandler):
    patterns = ["*.txt", "*.jpg"]

    def process(self, event):
        """
        event.event_type
            'modified' | 'created' | 'moved' | 'deleted'
        event.is_directory
            True | False
        event.src_path
            path/to/observed/file
        """
        # print(event.src_path, event.event_type)
        out = str(event.src_path)
        with open(out, "r") as t1:
            text = t1.read()
        print(out)
        print(text)

    def on_modified(self, event):
        self.process(event)

    def on_created(self, event):
        self.process(event)

async def observer_run():
    args = 'C:\\ForTest'
    observer = Observer()
    observer.schedule(MyHandler(), path=args if args else '.')
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()


async def main():
    dp.include_router(Handlers.user_router)
    await bot.delete_webhook(drop_pending_updates=True)
    await dp.start_polling(bot)


if __name__ == "__main__":
    asyncio.run(main())
    loop.run_until_complete(observer_run())
0

There are 0 best solutions below