python - 同步函数内的 asyncio.run 返回 None

标签 python multithreading asynchronous async-await python-asyncio

抱歉,如果看起来很基本,但我真的不明白为什么这返回 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()

最佳答案

why this returns 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)

关于python - 同步函数内的 asyncio.run 返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62228663/

相关文章:

javascript - 等待异步函数时是否需要显式捕获并重新抛出异常?

python - 绘制神经网络的基本示例

python - emacs elpy/jedi 代码完成 : popup window not working properly

java - 如何在 Java 中使用监视器(同步)

java - 在 Java 应用程序中使用触发器进行数据库轮询

asynchronous - 等待取消异步工作流

python - 如何在 Python 中将二维数组的字符串值转换为整数值?

python - 如何在 Python 3 中将字节转换为字符串

windows - SDL 2.0 : Create window in main thread, 但在单独的一个中进行所有渲染

python - 在 Python 中动态创建函数和线程