I’m trying to asyncio.create_task()
but I’m dealing with this error:
Here’s an example:
JavaScript
x
19
19
1
import asyncio
2
import time
3
4
async def async_say(delay, msg):
5
await asyncio.sleep(delay)
6
print(msg)
7
8
async def main():
9
task1 = asyncio.create_task(async_say(4, 'hello'))
10
task2 = asyncio.create_task(async_say(6, 'world'))
11
12
print(f"started at {time.strftime('%X')}")
13
await task1
14
await task2
15
print(f"finished at {time.strftime('%X')}")
16
17
loop = asyncio.get_event_loop()
18
loop.run_until_complete(main())
19
Out:
JavaScript
1
2
1
AttributeError: module 'asyncio' has no attribute 'create_task'
2
So I tried with the following code snippet (.ensure_future()
) instead, without any problem:
JavaScript
1
12
12
1
async def main():
2
task1 = asyncio.ensure_future(async_say(4, 'hello'))
3
task2 = asyncio.ensure_future(async_say(6, 'world'))
4
5
print(f"started at {time.strftime('%X')}")
6
await task1
7
await task2
8
print(f"finished at {time.strftime('%X')}")
9
10
loop = asyncio.get_event_loop()
11
loop.run_until_complete(main())
12
Out:
JavaScript
1
5
1
started at 13:19:44
2
hello
3
world
4
finished at 13:19:50
5
What’s wrong?
[NOTE]:
- Python 3.6
- Ubuntu 16.04
[UPDATE]:
With borrowing from @user4815162342 Answer, my problem solved:
JavaScript
1
13
13
1
async def main():
2
loop = asyncio.get_event_loop()
3
task1 = loop.create_task(async_say(4, 'hello'))
4
task2 = loop.create_task(async_say(6, 'world'))
5
6
print(f"started at {time.strftime('%X')}")
7
await task1
8
await task2
9
print(f"finished at {time.strftime('%X')}")
10
11
loop = asyncio.get_event_loop()
12
loop.run_until_complete(main())
13
Advertisement
Answer
The create_task
top-level function was added in Python 3.7, and you are using Python 3.6. Prior to 3.7, create_task
was only available as a method on the event loop, so you can invoke it like that:
JavaScript
1
8
1
async def main():
2
loop = asyncio.get_event_loop()
3
task1 = loop.create_task(async_say(4, 'hello'))
4
task2 = loop.create_task(async_say(6, 'world'))
5
# ...
6
await task1
7
await task2
8
That works in both 3.6 and 3.7, as well as in earlier versions. asyncio.ensure_future
will work as well, but when you know you’re dealing with a coroutine, create_task
is more explicit and is the preferred option.