diff --git a/ipyvuetify/extra/file_input.py b/ipyvuetify/extra/file_input.py index 30fb52b5..062111e6 100644 --- a/ipyvuetify/extra/file_input.py +++ b/ipyvuetify/extra/file_input.py @@ -5,7 +5,14 @@ import sys import IPython -import nest_asyncio + +try: + import nest_asyncio + + has_nest_asyncio = True +except ModuleNotFoundError: + has_nest_asyncio = False + import traitlets import ipyvuetify as v @@ -140,6 +147,21 @@ async def read_all(): self.widget.update_stats(self.file_index, chunk_size) await process_messages() + try: + # robust way to check if we already have an event loop + asyncio.get_event_loop() + except RuntimeError: + pass + else: + # we already have an event loop, so to be able to call asyncio.run(...) + # while also receiving messages from the frontend, we need to use nest_asyncio + if not has_nest_asyncio: + raise RuntimeError( + "nest_asyncio is required for FileInput when an event loop is already running in the current thread, " + "please run 'pip install nest_asyncio'." + ) + else: + nest_asyncio.apply() asyncio.run(read_all()) return size @@ -169,12 +191,6 @@ def __init__(self, **kwargs): self.stats = [] super().__init__(**kwargs) - if not hasattr(IPython.get_ipython(), "kernel"): - return - kernel = IPython.get_ipython().kernel - if kernel.implementation == "ipython": - nest_asyncio.apply() - @traitlets.observe("file_info") def _file_info_changed(self, _): self.version += 1