这个为什么报错呀,想了半天没有明白
import asyncioimport time
async def func1():
print("你好啊,我是1")
await asyncio.sleep(3)
print("你好啊,我是1")
async def func2():
print("你好啊,我是2")
await asyncio.sleep(2)
print("你好啊,我是2")
async def func3():
print("你好啊,我是3")
await asyncio.sleep(4)
print("你好啊,我是3")
if __name__ == '__main__':
f1 = func1()# 此时的函数是异步协程函数。此时函数执行得到的是一个协程对象
f2 = func2()
f3 = func3()
# asyncio.run(f1)#协程程序运行需要asyncio模块的支持
tasks = [
f1, f2, f3
]
t1 = time.time()
# 一次性启动多个任务(协程)
asyncio.run(asyncio.wait(tasks))
t2 = time.time()
print(t2 - t1)
这个python3.11的问题,python3.11直接传一个协程对象会报错,得传 task
参考文章:
https://blog.csdn.net/m0_69082030/article/details/124327891
https://stackoverflow.com/questions/58774718/asyncio-in-corroutine-runtimeerror-no-running-event-loop
参考代码:
import asyncio
import time
async def func1():
print("你好啊,我是1")
await asyncio.sleep(3)
print("你好啊,我是1")
async def func2():
print("你好啊,我是2")
await asyncio.sleep(2)
print("你好啊,我是2")
async def func3():
print("你好啊,我是3")
await asyncio.sleep(4)
print("你好啊,我是3")
if __name__ == '__main__':
f1 = func1()# 此时的函数是异步协程函数。此时函数执行得到的是一个协程对象
f2 = func2()
f3 = func3()
t1 = time.time()
loop = asyncio.new_event_loop()
tasks = [
loop.create_task(i) for i in
]
loop.run_until_complete(asyncio.wait(tasks))
t2 = time.time()
print(t2 - t1)
我运行没有问题 我这里正常运行
实在想不明白C:\Users\misaka\AppData\Local\Programs\Python\Python311\python.exe C:\Users\misaka\PycharmProjects\pythonProject\爬虫\第四章\协程.py
Traceback (most recent call last):
File "C:\Users\misaka\PycharmProjects\pythonProject\爬虫\第四章\协程.py", line 32, in <module>
asyncio.run(asyncio.wait(tasks))
File "C:\Users\misaka\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\misaka\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\misaka\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 650, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\misaka\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py", line 415, in wait
raise TypeError("Passing coroutines is forbidden, use tasks explicitly.")
TypeError: Passing coroutines is forbidden, use tasks explicitly.
sys:1: RuntimeWarning: coroutine 'func1' was never awaited
sys:1: RuntimeWarning: coroutine 'func2' was never awaited
sys:1: RuntimeWarning: coroutine 'func3' was never awaited
页:
[1]