Skip to content

Commit 6f2870a

Browse files
authored
Merge pull request #149 from oremanj/system-exit
Fix spurious error when asyncio.run() task raises SystemExit
2 parents 4ac0555 + d7987f1 commit 6f2870a

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

newsfragments/149.bugfix.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
trio-asyncio no longer raises a spurious "Event loop stopped before Future
2+
completed!" exception if a function passed to :func:`asyncio.run` calls
3+
:func:`sys.exit`.

tests/test_trio_asyncio.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,13 @@ def noop():
193193
await trio_asyncio.aio_as_trio(loop.run_in_executor)(executor, noop)
194194

195195
assert not scope.cancelled_caught
196+
197+
198+
def test_system_exit():
199+
async def main():
200+
raise SystemExit(42)
201+
202+
with pytest.raises(SystemExit) as scope:
203+
asyncio.run(main())
204+
205+
assert scope.value.code == 42

trio_asyncio/_sync.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,14 @@ def is_done(_):
139139
nonlocal result
140140

141141
result = outcome.capture(future.result)
142+
if isinstance(result, outcome.Error) and isinstance(
143+
result.error, (SystemExit, KeyboardInterrupt)
144+
):
145+
# These exceptions propagate out of the event loop;
146+
# don't stop the event loop again, or else it will
147+
# interfere with cleanup actions like
148+
# run_until_complete(shutdown_asyncgens)
149+
return
142150
self.stop()
143151

144152
future.add_done_callback(is_done)

0 commit comments

Comments
 (0)