Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # - Simple examples showing asynchronous workflow in Python -
- #****** 1. asyncio approach (Python>=3.4) ******
- # Pros: It's the closest one to JavaScript's async/await, so it's expected to be fully optimized.
- # Cons: Limited Python version support, spanning from still recent one. I wouldn't recommend it anyways since LTS isn't yet reached for it, so beware - it can be buggy sometimes.
- import asyncio
- @asyncio.coroutine
- def test_sleep(): # for Python>=3.5 can use "async def" without decorator above
- print("before")
- yield from asyncio.sleep(2) # for Python>=3.5 can use "await" instead
- print("after")
- @asyncio.coroutine
- def main():
- task = asyncio.create_task(test_sleep())
- yield from asyncio.sleep(1)
- print(1)
- yield from task
- asyncio.get_event_loop().run_until_complete(main()) # for Python>=3.6 can use this instead: asyncio.run(main())
- #****** 2. Threading approach ******
- # Pros: Long-term support, should work on all Python interpreters and versions in all environments.
- # Cons: It's overhead to do this for simple routines like below.
- from threading import Thread
- from time import sleep
- def test_sleep():
- print("before") # for Python 2 it's without parenthesis
- sleep(2)
- print("after")
- thread = Thread(target=test_sleep)
- thread.start()
- sleep(1)
- print(1)
- thread.join()
- #EOF
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement