Here's my attempt at a program that prematurely kills a subprocess using the high-level asyncio subprocess APIs:
import asyncio
async def test():
process = await asyncio.create_subprocess_shell(
"sleep 2 && echo done",
stdout=asyncio.subprocess.PIPE,
)
await asyncio.sleep(1)
process.kill()
await process.wait()
# process._transport.close()
asyncio.run(test())
On exit, it writes the following to stderr:
$ python3.9 test.py
Exception ignored in: <function BaseSubprocessTransport.__del__ at 0x1065f0dc0>
Traceback (most recent call last):
File "/usr/local/Cellar/python@3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_subprocess.py", line 126, in __del__
self.close()
File "/usr/local/Cellar/python@3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_subprocess.py", line 104, in close
proto.pipe.close()
File "/usr/local/Cellar/python@3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/unix_events.py", line 536, in close
self._close(None)
File "/usr/local/Cellar/python@3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/unix_events.py", line 560, in _close
self._loop.call_soon(self._call_connection_lost, exc)
File "/usr/local/Cellar/python@3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 746, in call_soon
self._check_closed()
File "/usr/local/Cellar/python@3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
If I uncomment # process._transport.close() or comment asyncio.sleep(1), the error disappears. (I get the same behavior in python 3.8. I haven't tried other python versions.)
Questions:
- Why do I need to explicitly close the
SubprocessTransport? - Can I use the high-level API to kill a subprocess cleanly without having to access the protected member
process._transport? Or am I forced to use the low-level API?