Сценарий Python выдает ошибку и завершает работу, OSError: [Errno 113] Не удалось выполнить соединение при сканировании портов с Asyncio - PullRequest
0 голосов
/ 14 мая 2019

Нашел этот интересный фрагмент кода на gist.github: https://gist.github.com/emillynge/1eee20e8429caece09774af7e5614d69

Он отлично работает, если удаленная сеть отвечает достаточно быстро, по умолчанию "timeout = 0.1".однако в реальном живом приложении это часто нужно поднимать.В частности, при сканировании диапазона сети этот сценарий выдает ошибку с тайм-аутом, равным 0,2, почти каждый раз.

Глядя на код, кажется, что сценарий должен игнорировать такие ошибки, но онфактически мгновенно прекращает работу.

     except (asyncio.TimeoutError, ConnectionRefusedError):
                pass
            else:
                yield task  # yield successful tasks

Вот полная ошибка, которую я получаю:

unhandled exception during asyncio.run() shutdown
task: <Task finished coro=<<async_generator_athrow without __name__>()> exception=RuntimeError("can't send non-None value to a just-started coroutine")>
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
    return future.result()
  File "port.py", line 130, in main
    async for task in streamer:
  File "/usr/local/lib/python3.7/site-packages/aiostream/stream/advanced.py", line 43, in base_combine
    result = getter()
  File "port.py", line 79, in task_worker
    await asyncio.wait_for(conn, task.timeout)
  File "/usr/local/lib/python3.7/asyncio/tasks.py", line 416, in wait_for
    return fut.result()
  File "/usr/local/lib/python3.7/asyncio/streams.py", line 77, in open_connection
    lambda: protocol, host, port, **kwds)
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 959, in create_connection
    raise exceptions[0]
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 946, in create_connection
    await self.sock_connect(sock, address)
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 464, in sock_connect
    return await fut
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 494, in _sock_connect_cb
    raise OSError(err, f'Connect call failed {address}')
OSError: [Errno 113] Connect call failed ('184.183.182.181', 8001)

During handling of the above exception, another exception occurred:

RuntimeError: can't send non-None value to a just-started coroutine
Traceback (most recent call last):
  File "port.py", line 153, in <module>
    asyncio.run(main(sys.argv[1], ''.join(sys.argv[2:])))
  File "/usr/local/lib/python3.7/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 584, in run_until_complete
    return future.result()
  File "port.py", line 130, in main
    async for task in streamer:
  File "/usr/local/lib/python3.7/site-packages/aiostream/stream/advanced.py", line 43, in base_combine
    result = getter()
  File "port.py", line 79, in task_worker
    await asyncio.wait_for(conn, task.timeout)
  File "/usr/local/lib/python3.7/asyncio/tasks.py", line 416, in wait_for
    return fut.result()
  File "/usr/local/lib/python3.7/asyncio/streams.py", line 77, in open_connection
    lambda: protocol, host, port, **kwds)
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 959, in create_connection
    raise exceptions[0]
  File "/usr/local/lib/python3.7/asyncio/base_events.py", line 946, in create_connection
    await self.sock_connect(sock, address)
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 464, in sock_connect
    return await fut
  File "/usr/local/lib/python3.7/asyncio/selector_events.py", line 494, in _sock_connect_cb
    raise OSError(err, f'Connect call failed {address}')
OSError: [Errno 113] Connect call failed ('184.183.182.181', 8001)

Цель - игнорировать ошибку и завершить цикл.Любой вклад приветствуется.

...