Update nest-asyncio/README.md
This commit is contained in:
@@ -1,15 +1,31 @@
|
|||||||
```python
|
```python
|
||||||
def sync(obj):
|
def sync(obj):
|
||||||
import asyncio, nest_asyncio; nest_asyncio.apply()
|
import asyncio, functools
|
||||||
if asyncio.iscoroutine(obj): return asyncio.run(obj)
|
if asyncio.iscoroutine(coro := obj):
|
||||||
if asyncio.iscoroutinefunction(func := obj):
|
loop, future = asyncio.get_event_loop(), asyncio.ensure_future(coro)
|
||||||
return lambda *args, **kwargs: sync(func(*args, **kwargs))
|
while not future.done():
|
||||||
|
loop._process_events(loop._selector.select(0))
|
||||||
|
if (ready := loop._ready) and not (handle := ready.popleft())._cancelled:
|
||||||
|
task = (tasks := asyncio.tasks._current_tasks).pop(loop, None)
|
||||||
|
handle._run()
|
||||||
|
tasks[loop] = task
|
||||||
|
return future.result()
|
||||||
|
if asyncio.iscoroutinefunction(func := obj): return functools.wraps(func)(
|
||||||
|
lambda *args, **kwargs: sync(func(*args, **kwargs)))
|
||||||
for attr in dir(obj):
|
for attr in dir(obj):
|
||||||
if asyncio.iscoroutinefunction(method := getattr(obj, attr)):
|
if asyncio.iscoroutinefunction(method := getattr(obj, attr)):
|
||||||
setattr(obj, attr, sync(method))
|
setattr(obj, attr, sync(method))
|
||||||
return obj
|
return obj
|
||||||
|
|
||||||
async def foo(): return 42
|
async def foo(): return 42
|
||||||
sync(foo()), sync(foo)()
|
print(sync(foo()), sync(foo)())
|
||||||
|
|
||||||
|
from playwright.async_api import async_playwright
|
||||||
|
browser = sync(sync(async_playwright().start()).firefox.launch())
|
||||||
|
page = sync(sync(browser.new_page()))
|
||||||
|
page._repr_png_ = page.screenshot
|
||||||
|
page.goto('https://naver.com')
|
||||||
|
page
|
||||||
```
|
```
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
|||||||
Reference in New Issue
Block a user