【问题标题】:Exception ignored in message on program exit程序退出消息中忽略的异常
【发布时间】:2017-05-11 06:06:48
【问题描述】:

我最初想在 Windows 上进行异步流通信。

from asyncio import *
from asyncio.subprocess import PIPE, STDOUT, DEVNULL
import sys

async def test(exe):
  inst = await create_subprocess_exec(exe, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
  inst.stdin.close()
  inst.wait()

# for subprocess' pipes on Windows
def initialize_async():
  if sys.platform == 'win32':
    set_event_loop(ProactorEventLoop())
  return get_event_loop()

loop = initialize_async()
loop.run_until_complete(test('attrib.exe'))
loop.close()

以上代码生成以下内容。

Exception ignored in: <bound method BaseSubprocessTransport.__del__ of <_WindowsSubprocessTransport closed pid=65088 running stdin=<_ProactorWritePipeTransport closed> stdout=<_ProactorReadPipeTransport closing fd=476 read=<_OverlappedFuture cancelled>>>>
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\asyncio\base_subprocess.py", line 132, in __del__
    self.close()
  File "C:\Program Files\Python36\lib\asyncio\base_subprocess.py", line 106, in close
    proto.pipe.close()
  File "C:\Program Files\Python36\lib\asyncio\proactor_events.py", line 84, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Program Files\Python36\lib\asyncio\base_events.py", line 573, in call_soon
    self._check_closed()
  File "C:\Program Files\Python36\lib\asyncio\base_events.py", line 357, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <object repr() failed>
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\asyncio\proactor_events.py", line 95, in __del__
    warnings.warn("unclosed transport %r" % self, ResourceWarning,
  File "C:\Program Files\Python36\lib\asyncio\proactor_events.py", line 54, in __repr__
    info.append('fd=%s' % self._sock.fileno())
  File "C:\Program Files\Python36\lib\asyncio\windows_utils.py", line 152, in fileno
    raise ValueError("I/O operatioon on closed pipe")
ValueError: I/O operatioon on closed pipe

如何消除此错误? stdin.close 和 wait 似乎还不够。

【问题讨论】:

    标签: python windows python-asyncio python-3.6


    【解决方案1】:

    请注意,与同步编程不同,许多 asyncio 函数实际上是应该等待的 coroutines。看看wait()是如何定义in documentation的:

    你应该修复你的代码来等待这个协程:

    async def test(exe):
      inst = await create_subprocess_exec(exe, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
    
      data = await inst.stdout.readline()  # readline, for example, is also coroutine.
      print(data)
    
      await inst.wait()
    

    您现在不会看到任何错误。

    【讨论】:

    • 我发现在 Linux 上替换为create_subprocess_shell,无论await inst.wait() 是否存在,都会引发确切的异常。不知道为什么。
    • 在 Mac OS 上面临同样的问题,同时终止一个创建了多个任务的子进程,即使我使用的是 terminate()wait() 的组合。
    猜你喜欢
    • 1970-01-01
    • 2014-06-10
    • 2019-01-20
    • 2016-10-28
    • 2019-08-31
    • 2015-02-02
    • 2021-07-20
    • 2011-04-16
    • 1970-01-01
    相关资源
    最近更新 更多