python - 在新线程中启动异步函数

标签 python python-3.x multithreading async-await python-asyncio

我正在尝试创建一个 discord 机器人,我需要在另一个新线程中运行一个异步函数,因为主线程需要运行另一个函数(Discord 客户端)

我要实现的目标:

# This methods needs to run in another thread
async def discord_async_method():
    while True:
        sleep(10)
        print("Hello World")
        ... # Discord Async Logic

# This needs to run in the main thread
client.run(TOKEN)

thread = ""

try:
    # This does not work, throws error "printHelloWorld Needs to be awaited"
    thread = Thread(target=discord_async_method)
    thread.start()
except (KeyboardInterrupt, SystemExit):

    # Stop Thread when CTRL + C is pressed or when program is exited
    thread.join()

我尝试过使用 asyncio 的其他解决方案,但我无法让其他解决方案起作用。

跟进:创建线程时,如何在停止程序(即 KeyboardInterupt 或 SystemExit)时停止该线程?

如有任何帮助,我们将不胜感激,谢谢!

最佳答案

在 asyncio 中,你不需要让线程来并行运行两个东西。在启动客户端之前,只需将协程作为任务提交到事件循环。

请注意,您的协程不得运行阻塞调用,因此您需要等待 asyncio.sleep() 而不是调用 sleep()。 (这通常是协程的情况,而不仅仅是不和谐的协程。)

async def discord_async_method():
    while True:
        await asyncio.sleep(10)
        print("Hello World")
        ... # Discord Async Logic

# run discord_async_method() in the "background"
asyncio.get_event_loop().create_task(discord_async_method())

client.run(TOKEN)

关于python - 在新线程中启动异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61151031/

相关文章:

string - Python 连接字符串以生成字符串中所有单词的组合

javascript - 来自 CryptoJS 和 Python Hashlib 的等效 MD5

python - 函数参数名以下划线开头

java - 如何在 Java 8 中使用 CompletableFuture 启动异步任务并让主线程完成并退出

c++ - PostThreadMessage 不起作用

python - 为什么具有名为 "del"、 "return"等的对象属性是语法错误?

python - 连接字符串列表中的选定字符串

c++ - 线程局部全局作用域变量

python - 使用 psycopg2 在 python 中连接到 PostgreSQL 时遇到问题

python - PySpark:计算按 AUC 分组