- Notifications
You must be signed in to change notification settings - Fork0
Run async code from sync code.
License
NotificationsYou must be signed in to change notification settings
lemon24/asyncio-thread-runner
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
you can have a little async (as a treat)
asyncio-thread-runner allows you to run async code from sync code.
This is useful when you're doing some sync stuff, but:
- you also need to do some async stuff,without makingeverything async
- maybe the sync stuff is an existing application
- maybe you still want to use your favorite sync library
- or maybe you need just a little async, without having to pay the full price
Features:
- unlikeasyncio.run(), it provides along-lived event loop
- unlikeasyncio.Runner, it runs in a dedicated thread, and you can use it frommultiple threads
- it allows you to useasync context managers anditerables from sync code
- check outthis article for why these are useful
Usage:
$ pip install asyncio-thread-runner
>>>asyncdefdouble(i):...returni*2...>>>fromasyncio_thread_runnerimportThreadRunner>>>runner=ThreadRunner()>>>runner.run(double(2))4
Annotated example:
importaiohttpfromasyncio_thread_runnerimportThreadRunner# you can use ThreadRunner as a context manager,# or call runner.close() when you're done with itwithThreadRunner()asrunner:# aiohttp.ClientSession() should be used as an async context manager,# enter_context() will exit the context on runner shutdown;# because instantiating ClientSession requires a running event loop,# we pass it as a factory instead of calling it in the main threadsession=runner.enter_context(aiohttp.ClientSession)# session.get() returns an async context manager...request=session.get('https://death.andgravity.com/asyncio-bridge')# which we turn into a normal one with wrap_context()withrunner.wrap_context(request)asresponse:# response.content is an async iterator;# we turn it into a normal iterator with wrap_iter()lines=list(runner.wrap_iter(response.content))# "got 935 lines"print('got',len(lines),'lines')
About
Run async code from sync code.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.