Search code examples
pythonpythonista

How to use asyncio in Pythonista3?


I tried to use asyncio in Pythonista3 (iPhone/iPad App) and got errors...

(Pythonista3: Python 3.6.1)

I used this movie as a reference and wrote a code;

import asyncio
import random

@asyncio.coroutine
asyncio def myCoroutine(id):
    process_time = random.randint(1, 5)
    await asyncio.sleep(process_time)
    print('Coroutine: {}. has successfully completed after {} seconds'.format(id, process_time))

@asyncio.coroutine
async def main():
    tasks = []
    for i in range(10):
        tasks.append(asyncio.ensure_future(myCoroutine(i)))
    await asyncio.gather(*tasks)

 
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

Error message is:

RuntimeWarning: coroutine 'main' was never awaited

I replaced (async def) > (def), but another error occurred:

await asyncio.sleep(process_time)

SyntaxError: invalid syntax

Additionally, I removed (@asyncio.coroutine), but another error occurred:

raise TypeError('A Future or coroutine is required')

Do you have any solutions?

Sincerely,


Solution

  • Fix the typo asyncio def -> async def on line 5 and remove the decorators (@asyncio.coroutine), and the code works.

    I tested this on Pythonista, but there is nothing specific to Pythonista as an environment here.