Python3.7.2中的asyncio.wait_for exec函数错误

时间:2019-03-08 07:29:04

标签: python python-3.x python-asyncio

我尝试运行以下代码:

import asyncio

async def eva(code):
    exec("async def ex(): return {}".format(code))
    return await asyncio.wait_for(locals()["ex"](), timeout=1.0)

async def main():
    while True:
        code = input()
        x = await asyncio.wait_for(eva(code), timeout=1.0)
        print(x)
asyncio.run(main())

并出现以下错误:

<module>

    asyncio.run(main())   File "C:\Users\\{user}\AppData\Local\Programs\Python\Python37\lib\asyncio\runners.py",
line 43, in run

    return loop.run_until_complete(main)   File "C:\Users\\{user}\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py",
line 584, in run_until_complete
    return future.result()

  File "eval.py", line 10, in main

    x = await asyncio.wait_for(eva(code), timeout=1.0)   File "C:\Users\\{user}\AppData\Local\Programs\Python\Python37\lib\asyncio\tasks.py",
line 416, in wait_for
    return fut.result()

  File "eval.py", line 5, in eva

    return await asyncio.wait_for(locals()["ex"](), timeout=1.0)

  File "C:\Users\\
{user}\AppData\Local\Programs\Python\Python37\lib\asyncio\tasks.py",
line 416, in wait_for

    return fut.result()

  File "<string>", line 1, in ex TypeError: 'int' object is not
iterable ```

您能帮我理解到底发生了什么吗?

1 个答案:

答案 0 :(得分:0)

从回溯中您可以看到函数ex发生了错误:

File "<string>", line 1, in ex

在执行此行之前不久:

File "eval.py", line 5, in eva
    return await asyncio.wait_for(locals()["ex"](), timeout=1.0)

换句话说,您从ex获得的协程locals()["ex"]内部某处引发了异常。


异常消息是:

  

TypeError:“ int”对象不可迭代

您可以在Google上搜索它,以了解何时可能发生的典型情况,但这也不难假设:ex中的某些内容试图迭代类型为int的对象。

类似的事情发生了:

import asyncio


async def ex():
    for i in 123:
        pass

async def main():
    return await asyncio.wait_for(ex(), timeout=1.0)


asyncio.run(main())

运行,您会看到类似的内容:

  File "...\main.py", line 15, in main
    return await asyncio.wait_for(ex(), timeout=1.0)
  File "...\python37\lib\asyncio\tasks.py", line 416, in wait_for
    return fut.result()
  File "...\main.py", line 11, in ex
    for i in 123:
TypeError: 'int' object is not iterable