Python 在线程内调用协程

Python 在线程内调用协程,python,python-3.x,Python,Python 3.x,是否可以使线程运行方法异步,以便在其中执行协同路由?我意识到我在混合范例——我正在尝试集成一个使用协同程序的第三方库,而我的项目使用线程。在我考虑更新我的项目使用CORUTIN之前,我想探索我的线程中执行的协同程序。 下面是我的示例用例,其中我有一个线程,但我想从线程中调用一个协程。我的问题是函数MyThread::run()似乎没有执行(打印)。我正在尝试的是可能的…和可取的吗 from threading import Thread class MyThread(Thread):

是否可以使线程运行方法异步,以便在其中执行协同路由?我意识到我在混合范例——我正在尝试集成一个使用协同程序的第三方库,而我的项目使用线程。在我考虑更新我的项目使用CORUTIN之前,我想探索我的线程中执行的协同程序。

下面是我的示例用例,其中我有一个线程,但我想从线程中调用一个协程。我的问题是函数
MyThread::run()
似乎没有执行(打印)。我正在尝试的是可能的…和可取的吗

from threading import Thread

class MyThread(Thread):

    def __init__(self):
        Thread.__init__(self)

        self.start()

    # def run(self):
    #   while True:
    #       print("MyThread::run() sync")

    async def run(self):
        while True:
            # This line isn't executing/printing
            print("MyThread::run() sync")

            # Call coroutine...
            # volume = await market_place.get_24h_volume()


try:
    t = MyThread()

    while True:
        pass
except KeyboardInterrupt:
    pass

您需要创建一个asyncio事件循环,并等待协同路由完成

import asyncio
from threading import Thread


class MyThread(Thread):
    def run(self):
        loop = asyncio.new_event_loop()  # loop = asyncio.get_event_loop()
        loop.run_until_complete(self._run())
        loop.close()
        # asyncio.run(self._run())    In Python 3.7+

    async def _run(self):
        while True:
            print("MyThread::run() sync")
            await asyncio.sleep(1)
            # OR
            # volume = await market_place.get_24h_volume()


t = MyThread()
t.start()
try:
    t.join()
except KeyboardInterrupt:
    pass

谢谢你的回答。当我运行代码时,没有显示打印输出。但是,如果我注释掉wait asyncio.sleep(1)它会多次显示打印输出
MyThread::run()sync
,因此线程正在运行。你能解释一下发生了什么事吗?为什么它不打印代码
wait asyncio.sleep(1)
?@JakeM它为我打印
MyThread::run()sync
。。您使用的是哪个版本的python?我用3.6.1进行了测试。我认为这缺少了一个
set\u event\u loop
调用。@astrojuanlu,代码与
set\u event\u loop
一起工作。也许你应该提及OP,以便通知他或她。