如何使用高级异步 API 干净地终止子进程?

问题描述

这是我尝试使用 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())

退出时,它将以下内容写入 stderr

$ python3.9 test.py

Exception ignored in: <function BaseSubprocesstransport.__del__ at 0x1065f0dc0>
Traceback (most recent call last):
  File "/usr/local/Cellar/[email protected]/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/[email protected]/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/[email protected]/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/[email protected]/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/[email protected]/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/[email protected]/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

如果我取消注释 # process._transport.close() 或注释 asyncio.sleep(1)错误就会消失。 (我在 python 3.8 中得到了相同的行为。我没有尝试过其他 python 版本。)

问题:

  1. 为什么我需要明确关闭 Subprocesstransport
  2. 是否可以使用高级 API 干净地终止子进程而无需访问受保护成员 process._transport?还是我被迫使用 low-level API

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)