【问题标题】:asyncio.run inside sync function returning None [duplicate]asyncio.run 内部同步函数返回无 [重复]
【发布时间】:2020-09-25 10:43:09
【问题描述】:

对不起,如果看起来很基本,但我真的不明白为什么这会返回 None:

import asyncio

def syncFunc():
    async def testAsync():
        return 'hello'
    asyncio.run(testAsync())

# in a different file:
x = syncFunc()
print(x)
# want to return 'hello'

如何从 asyncio.run 返回 'hello'?

这可行,但不是我想要的:

def syncFunc():
    async def testAsync():
         print('hello')
    asyncio.run(testAsync())

syncFunc()

【问题讨论】:

  • Python 函数默认返回None。将return 添加到syncFunc 即可获得结果。
  • 是的(我自己的facepaml)。我认为这是异步特定问题。谢谢!

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


【解决方案1】:

我可以这样做,分解asyncio.run()函数:

def syncFunc():
    async def testAsync():
        return 'hello'
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    result = loop.run_until_complete(testAsync())
    return result

x = syncFunc()
print(x)

显示“你好”。

asyncio.run() 的底层机制仍然是个谜。

【讨论】:

    【解决方案2】:

    为什么返回 None:

    因为在您的代码中 syncFunc 函数没有 return 语句。 这里有一个稍微不同的版本,可以满足你的需求:

    def syncFunc():
        async def testAsync():
            return 'hello'
        return asyncio.run(testAsync())  # return result of asyncio.run from syncFunc
    
    # in a different file:
    x = syncFunc()
    print(x)
    

    【讨论】:

      猜你喜欢
      • 2017-04-07
      • 2018-07-09
      • 2021-02-23
      • 2015-08-24
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多