Skip to content

Commit

Permalink
BUG: Add using nest-asyncio to fix the issue with running in Jupyter …
Browse files Browse the repository at this point in the history
…notebooks. [skip ci]
  • Loading branch information
Taher Chegini committed Jan 18, 2025
1 parent 046a306 commit 0511658
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ dependencies = [
"aiofiles",
"aiohttp>=3.8.3",
"click>=0.7",
"nest-asyncio",
"netcdf4",
"numpy>=2",
"pandas>=1",
Expand Down
32 changes: 26 additions & 6 deletions src/pygridmet/_streaming.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,33 @@ async def _stream_session(urls: Sequence[str], files: Sequence[Path]) -> None:
await asyncio.gather(*tasks)


def is_jupyter_kernel():
"""Check if the code is running in a Jupyter kernel (not IPython terminal)."""
try:
from IPython import get_ipython

ipython = get_ipython()
except (ImportError, NameError):
return False
if ipython is None:
return False
return "Terminal" not in ipython.__class__.__name__


def _get_or_create_event_loop() -> tuple[asyncio.AbstractEventLoop, bool]:
"""Retrieve or create an event loop."""
with contextlib.suppress(RuntimeError):
return asyncio.get_running_loop(), False
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
return new_loop, True
"""Create an event loop."""
try:
loop = asyncio.get_running_loop()
new_loop = False
except RuntimeError:
loop = asyncio.new_event_loop()
new_loop = True
asyncio.set_event_loop(loop)
if is_jupyter_kernel():
import nest_asyncio

nest_asyncio.apply(loop)
return loop, new_loop


def stream_write(urls: Sequence[str], file_paths: Sequence[Path]) -> None:
Expand Down

0 comments on commit 0511658

Please sign in to comment.