Skip to content

Commit bdcbbf3

Browse files
Add AsyncRunner.block_until_done (#444)
* Add `AsyncRunner.block_until_done` I have answered this question so often that I think it warrents a new method. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Use runner.block_until_done --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent a7f01eb commit bdcbbf3

File tree

3 files changed

+12
-5
lines changed

3 files changed

+12
-5
lines changed

adaptive/runner.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -722,6 +722,14 @@ def cancel(self) -> None:
722722
"""
723723
self.task.cancel()
724724

725+
def block_until_done(self) -> None:
726+
if in_ipynb():
727+
raise RuntimeError(
728+
"Cannot block the event loop when running in a Jupyter notebook."
729+
" Use `await runner.task` instead."
730+
)
731+
self.ioloop.run_until_complete(self.task)
732+
725733
def live_plot(
726734
self,
727735
*,

adaptive/tests/test_runner.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import asyncio
21
import platform
32
import sys
43
import time
@@ -34,7 +33,7 @@ def blocking_runner(learner, **kw):
3433

3534
def async_runner(learner, **kw):
3635
runner = AsyncRunner(learner, executor=SequentialExecutor(), **kw)
37-
asyncio.get_event_loop().run_until_complete(runner.task)
36+
runner.block_until_done()
3837

3938

4039
runners = [simple, blocking_runner, async_runner]
@@ -71,7 +70,7 @@ async def f(x):
7170

7271
learner = Learner1D(f, (-1, 1))
7372
runner = AsyncRunner(learner, npoints_goal=10)
74-
asyncio.get_event_loop().run_until_complete(runner.task)
73+
runner.block_until_done()
7574

7675

7776
# --- Test with different executors
@@ -158,7 +157,7 @@ def test_loky_executor(loky_executor):
158157
def test_default_executor():
159158
learner = Learner1D(linear, (-1, 1))
160159
runner = AsyncRunner(learner, npoints_goal=10)
161-
asyncio.get_event_loop().run_until_complete(runner.task)
160+
runner.block_until_done()
162161

163162

164163
def test_auto_goal():

docs/source/tutorial/tutorial.parallelism.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ if __name__ == "__main__":
8989
runner.start_periodic_saving(dict(fname=fname), interval=600)
9090

9191
# block until runner goal reached
92-
runner.ioloop.run_until_complete(runner.task)
92+
runner.block_until_done()
9393

9494
# save one final time before exiting
9595
learner.save(fname)

0 commit comments

Comments
 (0)