我正在嘗試為不和諧的機器人發出命令,使機器人執行可能很長的動作。所以我想在每個關鍵步驟之前發送一條訊息通知用戶。
但是,由于網路限制,發送訊息可能需要一些時間,因此會進一步減慢程式的速度。
作業代碼
當我呼叫不回傳值的函式時,它可以通過以下方式完美運行:
import discord
import requests
import asyncio
with requests.Session() as session:
await asyncio.gather(
ctx.send("Connecting to the server"),
init_session(session)
)
帶有字典的 TypeError
但是,問題是稍后,我使用了一個回傳字典的函式:
result = await asyncio.gather(
ctx.send("Connecting to the server"),
get_dict(session)
)
然后,它給了我以下錯誤: asyncio gather TypeError: unhashable type: 'dict'
帶有執行緒的 RunTimeError
我還嘗試send在另一個執行緒中執行該函式:
t = threading.Thread(target=asyncio.run, args=[ctx.send("Getting result")])
t.start()
但后來我還有另一個錯誤: RuntimeError: Task <Task pending name='Task-20' coro=<Messageable.send() running at [my discord library directory]> cb=[_run_until_complete_cb() at [my asyncio directory]\base_events.py:184]> got Future <Future pending> attached to a different loop
因此,如果有人知道更好的方法,我將非常感激。
uj5u.com熱心網友回復:
字典不是 的有效引數asyncio.gather,因為它需要一個可等待物件的串列。
如果您想保留get_dict當前定義的函式,則必須將其包裝到可等待物件中,即使用loop.run_in_executor:
loop = asyncio.get_running_loop()
result = await asyncio.gather(
ctx.send("Connecting to the server"),
loop.run_in_executor(None, get_dict, session)
)
uj5u.com熱心網友回復:
當您使用異步函式時,只允許某些回傳型別。這些型別需要是“可散列的”。可散列項不能直接編輯(如串列或字典),而是存盤的資料是恒定的(如元組或整數)(見這個答案)。
因此,您的錯誤的一個解決方案可以是為 get_dict 函式使用另一種資料型別(我想您也應該在這種情況下重命名該函式)。
如果您不想更改太多并且在創建后從不更改字典的任何內容,請考慮在回傳之前將其轉換為可散列版本。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422758.html
標籤:
下一篇:并行添加兩個陣列
