簡體   English   中英

asyncio create task and aiohttp, 'no running event loop'

[英]asyncio create task and aiohttp , 'no running event loop'

我正在嘗試使用 aiohttp 請求和 asyncio 任務制作一個 Pyqt5 應用程序。 我也在使用 quamash package,它需要 Python 3.7,所以我安裝了這個版本。(它在 Python 3.10 上不起作用)我使用 asyncio 和 quamash 的主要原因是因為我想做請求而不凍結應用程序的 GUI。

單擊“開始”按鈕並關閉應用程序時出現此錯誤:

Task exception was never retrieved
future: <Task finished coro=<App.rotator() done, defined at C:\Users\Zsolt\Documents\python-example\stack_exmaple.py:37> exception=RuntimeError('no running event loop')>
Traceback (most recent call last):
  File "C:\Users\Zsolt\Documents\python-example\stack_exmaple.py", line 41, in rotator
    response = await get()
  File "C:\Users\Zsolt\Documents\python-example\stack_exmaple.py", line 51, in get
    async with session.get(pokemon_url) as resp:
  File "C:\Users\Zsolt\AppData\Local\Programs\Python\Python37\lib\site-packages\aiohttp\client.py", line 1138, in __aenter__
    self._resp = await self._coro
  File "C:\Users\Zsolt\AppData\Local\Programs\Python\Python37\lib\site-packages\aiohttp\client.py", line 533, in _request
    async with ceil_timeout(real_timeout.connect):
  File "C:\Users\Zsolt\AppData\Local\Programs\Python\Python37\lib\site-packages\aiohttp\helpers.py", line 734, in ceil_timeout
    return async_timeout.timeout(None)
  File "C:\Users\Zsolt\AppData\Local\Programs\Python\Python37\lib\site-packages\async_timeout\__init__.py", line 30, in timeout
    loop = _get_running_loop()
  File "C:\Users\Zsolt\AppData\Local\Programs\Python\Python37\lib\site-packages\async_timeout\__init__.py", line 236, in _get_running_loop
    return asyncio.get_running_loop()
RuntimeError: no running event loop

這是完整的代碼:

from PyQt5.QtWidgets import *
from PyQt5.QtGui import QKeySequence, QPalette, QColor
from PyQt5.QtCore import Qt
from PyQt5 import QtGui, QtCore
import asyncio
import aiohttp
import quamash
import os.path
import json
import sys

class App(QWidget):

    run = 0
    response = ''
    def __init__(self, loop):
        super().__init__()

        btn = QPushButton('Start', self)
        btn.resize(btn.sizeHint())
        btn.clicked.connect(self.start)

        self.setGeometry(200, 200, 700, 400)
        self.display = QLabel(self)
        self.display.resize(200, 500)
        self.display.move(1, 50)

        self.count = 0
        self.show()
        self.loop = loop
        self.tasks = []
        self.tasks.append(loop.create_task(self.rotator()))

    async def rotator(self):
        while await asyncio.sleep(0, True):
            if (self.run == 1):
                self.count += 1
                response = await get()
                self.display.setText(str(response))
                  
    def start (self):
        self.run = 1            

async def get():
    async with aiohttp.ClientSession() as session:
        pokemon_url = 'https://pokeapi.co/api/v2/pokemon/151'
        async with session.get(pokemon_url) as resp:
            pokemon = await resp.json()
            print(pokemon)
            return pokemon
      
app = QApplication(sys.argv)
app.setApplicationName("Sample ;)")

loop = quamash.QEventLoop(app)
asyncio.set_event_loop(loop)

with loop:
    window = App(loop)
    window.show()
    loop.run_forever()

如果我注釋掉response = await get()它起作用,它會計算 self.count += 1 並在self.display.setText(str(self.count))上顯示變量。 但我需要讓它與 aiohttp 請求一起工作,所以它應該打印出請求的響應。

TLDR; 用 qasync 替換quamash

在 asyncio 中,執行異步代碼時始終存在任務。 就像在多線程程序中一樣,至少存在主線程。 如果 quamash 不遵守規則——這不是 aiohttp 問題。

quamash 不再維護,最新版本是 3.5 年前發布的。 維護的繼任者是 qasync,它沒有這個錯誤,並且可以完美地與最新的 aiohttp 配合使用。

FWIW,您也可以使用qtinter package 替換 quamash,它支持 Python 3.7 到 3.11。 免責聲明:我是qtinter的作者。)

使用qtinter ,最后幾行需要更改為以下內容:

app = QApplication(sys.argv)
app.setApplicationName("Sample ;)")

with qtinter.using_asyncio_from_qt():
    window = App(asyncio.get_running_loop())
    window.show()
    app.exec()

我通過安裝以前版本的 aiohttp 修復了錯誤 最初我安裝了 aiohttp 3.8.1.dist 並且我知道它之前在其他版本的 aiohttp 上對我有用,所以我查找了pypi.org/project/aiohttp/#history和原來我必須卸載 aiohttp 並安裝 aiohttp==3.7.4。

命令:

pip uninstall aiohttp
pip install aiohttp==3.7.4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM