@dronmaxman
VoIP Administrator

Как запустить два процесса на python?

Пишу бота на aiohttp, мне надо запустить два процесса, один это webhook для бота, второй это checker который раз в 10 секунд проверяет процессы и завершает их. Подскажите, где я ошибся?

import logging
from os import getenv

from aiohttp.web import run_app
from aiohttp.web_app import Application
from handlers import my_router
from routes import check_data_handler, demo_handler, send_message_handler, camera_poster, camera_poster_html, demo_handler_jpeg, camera_html, camera_stream_dash, check_processes

from aiogram import Bot, Dispatcher
from aiogram.types import MenuButtonWebApp, WebAppInfo, MenuButtonCommands
from aiogram.webhook.aiohttp_server import SimpleRequestHandler, setup_application

import aiohttp_jinja2
import jinja2
import asyncio
import time



TELEGRAM_TOKEN=getenv('TELEGRAM_TOKEN')
APP_BASE_URL=getenv('APP_BASE_URL')
APP_BASE_URL_PATH=getenv('APP_BASE_URL_PATH')


async def on_startup(bot: Bot, base_url: str):
    await bot.set_webhook(f"{base_url}/webhook")
    #await bot.delete_chat_menu_button()
    await bot.set_chat_menu_button(
        menu_button=MenuButtonCommands(text="Cameras", command="ipcam_show", type='commands')
    )


async def run_web():
    bot = Bot(token=TELEGRAM_TOKEN, parse_mode="HTML")
    dispatcher = Dispatcher()
    dispatcher["base_url"] = APP_BASE_URL + APP_BASE_URL_PATH
    dispatcher.startup.register(on_startup)

    dispatcher.include_router(my_router)

    app = Application()
    app["bot"] = bot

    app.router.add_get(APP_BASE_URL_PATH + "/demo", demo_handler)
    app.router.add_get(APP_BASE_URL_PATH + "/demo.html", demo_handler)

    SimpleRequestHandler(
        dispatcher=dispatcher,
        bot=bot,
    ).register(app, path=APP_BASE_URL_PATH + "/webhook")
    setup_application(app, dispatcher, bot=bot)

    aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('html'))
    
    await run_app(app, host="0.0.0.0", port=8081)


async def run_checker():
    while True:
        print("Run task process check")
        await check_processes()
        await asyncio.sleep(10)


async def main():
    tasks = [
        asyncio.create_task(run_checker()),
        asyncio.create_task(run_web())
    ]
    await asyncio.gather(*tasks)

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Checker объявлен в другом файле
async def check_processes():
   # while True:
    for camera_id, process in list(processes.items()):
        if process.poll() is not None:
            # Если процесс завершился, удаляем его из словаря
            del processes[camera_id]
            logging.info(f"Процесс для камеры {camera_id} завершен")


Получаю ошибку
Traceback (most recent call last):
  File "/Users/valya/Projects/bot_ipcam/aiogram/examples/web_app/main.py", line 86, in <module>
    loop.run_until_complete(main())
  File "/opt/homebrew/Cellar/python@3.10/3.10.10_1/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/Users/valya/Projects/bot_ipcam/aiogram/examples/web_app/main.py", line 81, in main
    await asyncio.gather(*tasks)
  File "/Users/valya/Projects/bot_ipcam/aiogram/examples/web_app/main.py", line 64, in run_web
    await run_app(app, host="0.0.0.0", port=8081)
  File "/Users/valya/Projects/bot_ipcam/aiogram/examples/web_app/.venv/lib/python3.10/site-packages/aiohttp/web.py", line 520, in run_app
    _cancel_tasks({main_task}, loop)
  File "/Users/valya/Projects/bot_ipcam/aiogram/examples/web_app/.venv/lib/python3.10/site-packages/aiohttp/web.py", line 447, in _cancel_tasks
    loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True))
  File "/opt/homebrew/Cellar/python@3.10/3.10.10_1/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py", line 625, in run_until_complete
    self._check_running()
  File "/opt/homebrew/Cellar/python@3.10/3.10.10_1/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py", line 586, in _check_running
    raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running
  • Вопрос задан
  • 317 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы