Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- micromamba_root/envs/pytorch_env/Lib/asyncio/__init__.py +46 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/__main__.py +127 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/base_events.py +1961 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/base_futures.py +68 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/base_subprocess.py +285 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/base_tasks.py +92 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/constants.py +38 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/coroutines.py +111 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/events.py +846 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/exceptions.py +62 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/format_helpers.py +76 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/futures.py +428 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/locks.py +587 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/log.py +7 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/mixins.py +21 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/proactor_events.py +894 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/protocols.py +216 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/queues.py +244 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/runners.py +211 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/selector_events.py +1246 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/sslproto.py +926 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/staggered.py +149 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/streams.py +768 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/subprocess.py +228 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/taskgroups.py +234 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/tasks.py +990 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/threads.py +25 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/timeouts.py +168 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/transports.py +335 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/trsock.py +98 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/unix_events.py +1476 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/windows_events.py +952 -0
- micromamba_root/envs/pytorch_env/Lib/asyncio/windows_utils.py +173 -0
- micromamba_root/envs/pytorch_env/Lib/collections/__init__.py +1576 -0
- micromamba_root/envs/pytorch_env/Lib/collections/abc.py +3 -0
- micromamba_root/envs/pytorch_env/Lib/concurrent/__init__.py +1 -0
- micromamba_root/envs/pytorch_env/Lib/ctypes/__init__.py +566 -0
- micromamba_root/envs/pytorch_env/Lib/ctypes/_aix.py +331 -0
- micromamba_root/envs/pytorch_env/Lib/ctypes/_endian.py +78 -0
- micromamba_root/envs/pytorch_env/Lib/ctypes/util.py +400 -0
- micromamba_root/envs/pytorch_env/Lib/ctypes/wintypes.py +202 -0
- micromamba_root/envs/pytorch_env/Lib/curses/__init__.py +101 -0
- micromamba_root/envs/pytorch_env/Lib/curses/ascii.py +99 -0
- micromamba_root/envs/pytorch_env/Lib/curses/has_key.py +192 -0
- micromamba_root/envs/pytorch_env/Lib/curses/panel.py +6 -0
- micromamba_root/envs/pytorch_env/Lib/curses/textpad.py +201 -0
- micromamba_root/envs/pytorch_env/Lib/dbm/__init__.py +190 -0
- micromamba_root/envs/pytorch_env/Lib/dbm/dumb.py +317 -0
- micromamba_root/envs/pytorch_env/Lib/dbm/gnu.py +3 -0
- micromamba_root/envs/pytorch_env/Lib/dbm/ndbm.py +3 -0
micromamba_root/envs/pytorch_env/Lib/asyncio/__init__.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The asyncio package, tracking PEP 3156."""
|
| 2 |
+
|
| 3 |
+
# flake8: noqa
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
# This relies on each of the submodules having an __all__ variable.
|
| 8 |
+
from .base_events import *
|
| 9 |
+
from .coroutines import *
|
| 10 |
+
from .events import *
|
| 11 |
+
from .exceptions import *
|
| 12 |
+
from .futures import *
|
| 13 |
+
from .locks import *
|
| 14 |
+
from .protocols import *
|
| 15 |
+
from .runners import *
|
| 16 |
+
from .queues import *
|
| 17 |
+
from .streams import *
|
| 18 |
+
from .subprocess import *
|
| 19 |
+
from .tasks import *
|
| 20 |
+
from .taskgroups import *
|
| 21 |
+
from .timeouts import *
|
| 22 |
+
from .threads import *
|
| 23 |
+
from .transports import *
|
| 24 |
+
|
| 25 |
+
__all__ = (base_events.__all__ +
|
| 26 |
+
coroutines.__all__ +
|
| 27 |
+
events.__all__ +
|
| 28 |
+
exceptions.__all__ +
|
| 29 |
+
futures.__all__ +
|
| 30 |
+
locks.__all__ +
|
| 31 |
+
protocols.__all__ +
|
| 32 |
+
runners.__all__ +
|
| 33 |
+
queues.__all__ +
|
| 34 |
+
streams.__all__ +
|
| 35 |
+
subprocess.__all__ +
|
| 36 |
+
tasks.__all__ +
|
| 37 |
+
threads.__all__ +
|
| 38 |
+
timeouts.__all__ +
|
| 39 |
+
transports.__all__)
|
| 40 |
+
|
| 41 |
+
if sys.platform == 'win32': # pragma: no cover
|
| 42 |
+
from .windows_events import *
|
| 43 |
+
__all__ += windows_events.__all__
|
| 44 |
+
else:
|
| 45 |
+
from .unix_events import * # pragma: no cover
|
| 46 |
+
__all__ += unix_events.__all__
|
micromamba_root/envs/pytorch_env/Lib/asyncio/__main__.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ast
|
| 2 |
+
import asyncio
|
| 3 |
+
import code
|
| 4 |
+
import concurrent.futures
|
| 5 |
+
import inspect
|
| 6 |
+
import sys
|
| 7 |
+
import threading
|
| 8 |
+
import types
|
| 9 |
+
import warnings
|
| 10 |
+
|
| 11 |
+
from . import futures
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class AsyncIOInteractiveConsole(code.InteractiveConsole):
|
| 15 |
+
|
| 16 |
+
def __init__(self, locals, loop):
|
| 17 |
+
super().__init__(locals)
|
| 18 |
+
self.compile.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
|
| 19 |
+
|
| 20 |
+
self.loop = loop
|
| 21 |
+
|
| 22 |
+
def runcode(self, code):
|
| 23 |
+
future = concurrent.futures.Future()
|
| 24 |
+
|
| 25 |
+
def callback():
|
| 26 |
+
global repl_future
|
| 27 |
+
global repl_future_interrupted
|
| 28 |
+
|
| 29 |
+
repl_future = None
|
| 30 |
+
repl_future_interrupted = False
|
| 31 |
+
|
| 32 |
+
func = types.FunctionType(code, self.locals)
|
| 33 |
+
try:
|
| 34 |
+
coro = func()
|
| 35 |
+
except SystemExit:
|
| 36 |
+
raise
|
| 37 |
+
except KeyboardInterrupt as ex:
|
| 38 |
+
repl_future_interrupted = True
|
| 39 |
+
future.set_exception(ex)
|
| 40 |
+
return
|
| 41 |
+
except BaseException as ex:
|
| 42 |
+
future.set_exception(ex)
|
| 43 |
+
return
|
| 44 |
+
|
| 45 |
+
if not inspect.iscoroutine(coro):
|
| 46 |
+
future.set_result(coro)
|
| 47 |
+
return
|
| 48 |
+
|
| 49 |
+
try:
|
| 50 |
+
repl_future = self.loop.create_task(coro)
|
| 51 |
+
futures._chain_future(repl_future, future)
|
| 52 |
+
except BaseException as exc:
|
| 53 |
+
future.set_exception(exc)
|
| 54 |
+
|
| 55 |
+
loop.call_soon_threadsafe(callback)
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
return future.result()
|
| 59 |
+
except SystemExit:
|
| 60 |
+
raise
|
| 61 |
+
except BaseException:
|
| 62 |
+
if repl_future_interrupted:
|
| 63 |
+
self.write("\nKeyboardInterrupt\n")
|
| 64 |
+
else:
|
| 65 |
+
self.showtraceback()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class REPLThread(threading.Thread):
|
| 69 |
+
|
| 70 |
+
def run(self):
|
| 71 |
+
try:
|
| 72 |
+
banner = (
|
| 73 |
+
f'asyncio REPL {sys.version} on {sys.platform}\n'
|
| 74 |
+
f'Use "await" directly instead of "asyncio.run()".\n'
|
| 75 |
+
f'Type "help", "copyright", "credits" or "license" '
|
| 76 |
+
f'for more information.\n'
|
| 77 |
+
f'{getattr(sys, "ps1", ">>> ")}import asyncio'
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
console.interact(
|
| 81 |
+
banner=banner,
|
| 82 |
+
exitmsg='exiting asyncio REPL...')
|
| 83 |
+
finally:
|
| 84 |
+
warnings.filterwarnings(
|
| 85 |
+
'ignore',
|
| 86 |
+
message=r'^coroutine .* was never awaited$',
|
| 87 |
+
category=RuntimeWarning)
|
| 88 |
+
|
| 89 |
+
loop.call_soon_threadsafe(loop.stop)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
if __name__ == '__main__':
|
| 93 |
+
sys.audit("cpython.run_stdin")
|
| 94 |
+
|
| 95 |
+
loop = asyncio.new_event_loop()
|
| 96 |
+
asyncio.set_event_loop(loop)
|
| 97 |
+
|
| 98 |
+
repl_locals = {'asyncio': asyncio}
|
| 99 |
+
for key in {'__name__', '__package__',
|
| 100 |
+
'__loader__', '__spec__',
|
| 101 |
+
'__builtins__', '__file__'}:
|
| 102 |
+
repl_locals[key] = locals()[key]
|
| 103 |
+
|
| 104 |
+
console = AsyncIOInteractiveConsole(repl_locals, loop)
|
| 105 |
+
|
| 106 |
+
repl_future = None
|
| 107 |
+
repl_future_interrupted = False
|
| 108 |
+
|
| 109 |
+
try:
|
| 110 |
+
import readline # NoQA
|
| 111 |
+
except ImportError:
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
repl_thread = REPLThread()
|
| 115 |
+
repl_thread.daemon = True
|
| 116 |
+
repl_thread.start()
|
| 117 |
+
|
| 118 |
+
while True:
|
| 119 |
+
try:
|
| 120 |
+
loop.run_forever()
|
| 121 |
+
except KeyboardInterrupt:
|
| 122 |
+
if repl_future and not repl_future.done():
|
| 123 |
+
repl_future.cancel()
|
| 124 |
+
repl_future_interrupted = True
|
| 125 |
+
continue
|
| 126 |
+
else:
|
| 127 |
+
break
|
micromamba_root/envs/pytorch_env/Lib/asyncio/base_events.py
ADDED
|
@@ -0,0 +1,1961 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Base implementation of event loop.
|
| 2 |
+
|
| 3 |
+
The event loop can be broken up into a multiplexer (the part
|
| 4 |
+
responsible for notifying us of I/O events) and the event loop proper,
|
| 5 |
+
which wraps a multiplexer with functionality for scheduling callbacks,
|
| 6 |
+
immediately or at a given time in the future.
|
| 7 |
+
|
| 8 |
+
Whenever a public API takes a callback, subsequent positional
|
| 9 |
+
arguments will be passed to the callback if/when it is called. This
|
| 10 |
+
avoids the proliferation of trivial lambdas implementing closures.
|
| 11 |
+
Keyword arguments for the callback are not supported; this is a
|
| 12 |
+
conscious design decision, leaving the door open for keyword arguments
|
| 13 |
+
to modify the meaning of the API call itself.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import collections
|
| 17 |
+
import collections.abc
|
| 18 |
+
import concurrent.futures
|
| 19 |
+
import errno
|
| 20 |
+
import functools
|
| 21 |
+
import heapq
|
| 22 |
+
import itertools
|
| 23 |
+
import os
|
| 24 |
+
import socket
|
| 25 |
+
import stat
|
| 26 |
+
import subprocess
|
| 27 |
+
import threading
|
| 28 |
+
import time
|
| 29 |
+
import traceback
|
| 30 |
+
import sys
|
| 31 |
+
import warnings
|
| 32 |
+
import weakref
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
import ssl
|
| 36 |
+
except ImportError: # pragma: no cover
|
| 37 |
+
ssl = None
|
| 38 |
+
|
| 39 |
+
from . import constants
|
| 40 |
+
from . import coroutines
|
| 41 |
+
from . import events
|
| 42 |
+
from . import exceptions
|
| 43 |
+
from . import futures
|
| 44 |
+
from . import protocols
|
| 45 |
+
from . import sslproto
|
| 46 |
+
from . import staggered
|
| 47 |
+
from . import tasks
|
| 48 |
+
from . import transports
|
| 49 |
+
from . import trsock
|
| 50 |
+
from .log import logger
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
__all__ = 'BaseEventLoop','Server',
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# Minimum number of _scheduled timer handles before cleanup of
|
| 57 |
+
# cancelled handles is performed.
|
| 58 |
+
_MIN_SCHEDULED_TIMER_HANDLES = 100
|
| 59 |
+
|
| 60 |
+
# Minimum fraction of _scheduled timer handles that are cancelled
|
| 61 |
+
# before cleanup of cancelled handles is performed.
|
| 62 |
+
_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
_HAS_IPv6 = hasattr(socket, 'AF_INET6')
|
| 66 |
+
|
| 67 |
+
# Maximum timeout passed to select to avoid OS limitations
|
| 68 |
+
MAXIMUM_SELECT_TIMEOUT = 24 * 3600
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _format_handle(handle):
|
| 72 |
+
cb = handle._callback
|
| 73 |
+
if isinstance(getattr(cb, '__self__', None), tasks.Task):
|
| 74 |
+
# format the task
|
| 75 |
+
return repr(cb.__self__)
|
| 76 |
+
else:
|
| 77 |
+
return str(handle)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _format_pipe(fd):
|
| 81 |
+
if fd == subprocess.PIPE:
|
| 82 |
+
return '<pipe>'
|
| 83 |
+
elif fd == subprocess.STDOUT:
|
| 84 |
+
return '<stdout>'
|
| 85 |
+
else:
|
| 86 |
+
return repr(fd)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _set_reuseport(sock):
|
| 90 |
+
if not hasattr(socket, 'SO_REUSEPORT'):
|
| 91 |
+
raise ValueError('reuse_port not supported by socket module')
|
| 92 |
+
else:
|
| 93 |
+
try:
|
| 94 |
+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
|
| 95 |
+
except OSError:
|
| 96 |
+
raise ValueError('reuse_port not supported by socket module, '
|
| 97 |
+
'SO_REUSEPORT defined but not implemented.')
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _ipaddr_info(host, port, family, type, proto, flowinfo=0, scopeid=0):
|
| 101 |
+
# Try to skip getaddrinfo if "host" is already an IP. Users might have
|
| 102 |
+
# handled name resolution in their own code and pass in resolved IPs.
|
| 103 |
+
if not hasattr(socket, 'inet_pton'):
|
| 104 |
+
return
|
| 105 |
+
|
| 106 |
+
if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
|
| 107 |
+
host is None:
|
| 108 |
+
return None
|
| 109 |
+
|
| 110 |
+
if type == socket.SOCK_STREAM:
|
| 111 |
+
proto = socket.IPPROTO_TCP
|
| 112 |
+
elif type == socket.SOCK_DGRAM:
|
| 113 |
+
proto = socket.IPPROTO_UDP
|
| 114 |
+
else:
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
if port is None:
|
| 118 |
+
port = 0
|
| 119 |
+
elif isinstance(port, bytes) and port == b'':
|
| 120 |
+
port = 0
|
| 121 |
+
elif isinstance(port, str) and port == '':
|
| 122 |
+
port = 0
|
| 123 |
+
else:
|
| 124 |
+
# If port's a service name like "http", don't skip getaddrinfo.
|
| 125 |
+
try:
|
| 126 |
+
port = int(port)
|
| 127 |
+
except (TypeError, ValueError):
|
| 128 |
+
return None
|
| 129 |
+
|
| 130 |
+
if family == socket.AF_UNSPEC:
|
| 131 |
+
afs = [socket.AF_INET]
|
| 132 |
+
if _HAS_IPv6:
|
| 133 |
+
afs.append(socket.AF_INET6)
|
| 134 |
+
else:
|
| 135 |
+
afs = [family]
|
| 136 |
+
|
| 137 |
+
if isinstance(host, bytes):
|
| 138 |
+
host = host.decode('idna')
|
| 139 |
+
if '%' in host:
|
| 140 |
+
# Linux's inet_pton doesn't accept an IPv6 zone index after host,
|
| 141 |
+
# like '::1%lo0'.
|
| 142 |
+
return None
|
| 143 |
+
|
| 144 |
+
for af in afs:
|
| 145 |
+
try:
|
| 146 |
+
socket.inet_pton(af, host)
|
| 147 |
+
# The host has already been resolved.
|
| 148 |
+
if _HAS_IPv6 and af == socket.AF_INET6:
|
| 149 |
+
return af, type, proto, '', (host, port, flowinfo, scopeid)
|
| 150 |
+
else:
|
| 151 |
+
return af, type, proto, '', (host, port)
|
| 152 |
+
except OSError:
|
| 153 |
+
pass
|
| 154 |
+
|
| 155 |
+
# "host" is not an IP address.
|
| 156 |
+
return None
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _interleave_addrinfos(addrinfos, first_address_family_count=1):
|
| 160 |
+
"""Interleave list of addrinfo tuples by family."""
|
| 161 |
+
# Group addresses by family
|
| 162 |
+
addrinfos_by_family = collections.OrderedDict()
|
| 163 |
+
for addr in addrinfos:
|
| 164 |
+
family = addr[0]
|
| 165 |
+
if family not in addrinfos_by_family:
|
| 166 |
+
addrinfos_by_family[family] = []
|
| 167 |
+
addrinfos_by_family[family].append(addr)
|
| 168 |
+
addrinfos_lists = list(addrinfos_by_family.values())
|
| 169 |
+
|
| 170 |
+
reordered = []
|
| 171 |
+
if first_address_family_count > 1:
|
| 172 |
+
reordered.extend(addrinfos_lists[0][:first_address_family_count - 1])
|
| 173 |
+
del addrinfos_lists[0][:first_address_family_count - 1]
|
| 174 |
+
reordered.extend(
|
| 175 |
+
a for a in itertools.chain.from_iterable(
|
| 176 |
+
itertools.zip_longest(*addrinfos_lists)
|
| 177 |
+
) if a is not None)
|
| 178 |
+
return reordered
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _run_until_complete_cb(fut):
|
| 182 |
+
if not fut.cancelled():
|
| 183 |
+
exc = fut.exception()
|
| 184 |
+
if isinstance(exc, (SystemExit, KeyboardInterrupt)):
|
| 185 |
+
# Issue #22429: run_forever() already finished, no need to
|
| 186 |
+
# stop it.
|
| 187 |
+
return
|
| 188 |
+
futures._get_loop(fut).stop()
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
if hasattr(socket, 'TCP_NODELAY'):
|
| 192 |
+
def _set_nodelay(sock):
|
| 193 |
+
if (sock.family in {socket.AF_INET, socket.AF_INET6} and
|
| 194 |
+
sock.type == socket.SOCK_STREAM and
|
| 195 |
+
sock.proto == socket.IPPROTO_TCP):
|
| 196 |
+
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
|
| 197 |
+
else:
|
| 198 |
+
def _set_nodelay(sock):
|
| 199 |
+
pass
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _check_ssl_socket(sock):
|
| 203 |
+
if ssl is not None and isinstance(sock, ssl.SSLSocket):
|
| 204 |
+
raise TypeError("Socket cannot be of type SSLSocket")
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class _SendfileFallbackProtocol(protocols.Protocol):
|
| 208 |
+
def __init__(self, transp):
|
| 209 |
+
if not isinstance(transp, transports._FlowControlMixin):
|
| 210 |
+
raise TypeError("transport should be _FlowControlMixin instance")
|
| 211 |
+
self._transport = transp
|
| 212 |
+
self._proto = transp.get_protocol()
|
| 213 |
+
self._should_resume_reading = transp.is_reading()
|
| 214 |
+
self._should_resume_writing = transp._protocol_paused
|
| 215 |
+
transp.pause_reading()
|
| 216 |
+
transp.set_protocol(self)
|
| 217 |
+
if self._should_resume_writing:
|
| 218 |
+
self._write_ready_fut = self._transport._loop.create_future()
|
| 219 |
+
else:
|
| 220 |
+
self._write_ready_fut = None
|
| 221 |
+
|
| 222 |
+
async def drain(self):
|
| 223 |
+
if self._transport.is_closing():
|
| 224 |
+
raise ConnectionError("Connection closed by peer")
|
| 225 |
+
fut = self._write_ready_fut
|
| 226 |
+
if fut is None:
|
| 227 |
+
return
|
| 228 |
+
await fut
|
| 229 |
+
|
| 230 |
+
def connection_made(self, transport):
|
| 231 |
+
raise RuntimeError("Invalid state: "
|
| 232 |
+
"connection should have been established already.")
|
| 233 |
+
|
| 234 |
+
def connection_lost(self, exc):
|
| 235 |
+
if self._write_ready_fut is not None:
|
| 236 |
+
# Never happens if peer disconnects after sending the whole content
|
| 237 |
+
# Thus disconnection is always an exception from user perspective
|
| 238 |
+
if exc is None:
|
| 239 |
+
self._write_ready_fut.set_exception(
|
| 240 |
+
ConnectionError("Connection is closed by peer"))
|
| 241 |
+
else:
|
| 242 |
+
self._write_ready_fut.set_exception(exc)
|
| 243 |
+
self._proto.connection_lost(exc)
|
| 244 |
+
|
| 245 |
+
def pause_writing(self):
|
| 246 |
+
if self._write_ready_fut is not None:
|
| 247 |
+
return
|
| 248 |
+
self._write_ready_fut = self._transport._loop.create_future()
|
| 249 |
+
|
| 250 |
+
def resume_writing(self):
|
| 251 |
+
if self._write_ready_fut is None:
|
| 252 |
+
return
|
| 253 |
+
self._write_ready_fut.set_result(False)
|
| 254 |
+
self._write_ready_fut = None
|
| 255 |
+
|
| 256 |
+
def data_received(self, data):
|
| 257 |
+
raise RuntimeError("Invalid state: reading should be paused")
|
| 258 |
+
|
| 259 |
+
def eof_received(self):
|
| 260 |
+
raise RuntimeError("Invalid state: reading should be paused")
|
| 261 |
+
|
| 262 |
+
async def restore(self):
|
| 263 |
+
self._transport.set_protocol(self._proto)
|
| 264 |
+
if self._should_resume_reading:
|
| 265 |
+
self._transport.resume_reading()
|
| 266 |
+
if self._write_ready_fut is not None:
|
| 267 |
+
# Cancel the future.
|
| 268 |
+
# Basically it has no effect because protocol is switched back,
|
| 269 |
+
# no code should wait for it anymore.
|
| 270 |
+
self._write_ready_fut.cancel()
|
| 271 |
+
if self._should_resume_writing:
|
| 272 |
+
self._proto.resume_writing()
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class Server(events.AbstractServer):
|
| 276 |
+
|
| 277 |
+
def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
|
| 278 |
+
ssl_handshake_timeout, ssl_shutdown_timeout=None):
|
| 279 |
+
self._loop = loop
|
| 280 |
+
self._sockets = sockets
|
| 281 |
+
self._active_count = 0
|
| 282 |
+
self._waiters = []
|
| 283 |
+
self._protocol_factory = protocol_factory
|
| 284 |
+
self._backlog = backlog
|
| 285 |
+
self._ssl_context = ssl_context
|
| 286 |
+
self._ssl_handshake_timeout = ssl_handshake_timeout
|
| 287 |
+
self._ssl_shutdown_timeout = ssl_shutdown_timeout
|
| 288 |
+
self._serving = False
|
| 289 |
+
self._serving_forever_fut = None
|
| 290 |
+
|
| 291 |
+
def __repr__(self):
|
| 292 |
+
return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
|
| 293 |
+
|
| 294 |
+
def _attach(self):
|
| 295 |
+
assert self._sockets is not None
|
| 296 |
+
self._active_count += 1
|
| 297 |
+
|
| 298 |
+
def _detach(self):
|
| 299 |
+
assert self._active_count > 0
|
| 300 |
+
self._active_count -= 1
|
| 301 |
+
if self._active_count == 0 and self._sockets is None:
|
| 302 |
+
self._wakeup()
|
| 303 |
+
|
| 304 |
+
def _wakeup(self):
|
| 305 |
+
waiters = self._waiters
|
| 306 |
+
self._waiters = None
|
| 307 |
+
for waiter in waiters:
|
| 308 |
+
if not waiter.done():
|
| 309 |
+
waiter.set_result(waiter)
|
| 310 |
+
|
| 311 |
+
def _start_serving(self):
|
| 312 |
+
if self._serving:
|
| 313 |
+
return
|
| 314 |
+
self._serving = True
|
| 315 |
+
for sock in self._sockets:
|
| 316 |
+
sock.listen(self._backlog)
|
| 317 |
+
self._loop._start_serving(
|
| 318 |
+
self._protocol_factory, sock, self._ssl_context,
|
| 319 |
+
self, self._backlog, self._ssl_handshake_timeout,
|
| 320 |
+
self._ssl_shutdown_timeout)
|
| 321 |
+
|
| 322 |
+
def get_loop(self):
|
| 323 |
+
return self._loop
|
| 324 |
+
|
| 325 |
+
def is_serving(self):
|
| 326 |
+
return self._serving
|
| 327 |
+
|
| 328 |
+
@property
|
| 329 |
+
def sockets(self):
|
| 330 |
+
if self._sockets is None:
|
| 331 |
+
return ()
|
| 332 |
+
return tuple(trsock.TransportSocket(s) for s in self._sockets)
|
| 333 |
+
|
| 334 |
+
def close(self):
|
| 335 |
+
sockets = self._sockets
|
| 336 |
+
if sockets is None:
|
| 337 |
+
return
|
| 338 |
+
self._sockets = None
|
| 339 |
+
|
| 340 |
+
for sock in sockets:
|
| 341 |
+
self._loop._stop_serving(sock)
|
| 342 |
+
|
| 343 |
+
self._serving = False
|
| 344 |
+
|
| 345 |
+
if (self._serving_forever_fut is not None and
|
| 346 |
+
not self._serving_forever_fut.done()):
|
| 347 |
+
self._serving_forever_fut.cancel()
|
| 348 |
+
self._serving_forever_fut = None
|
| 349 |
+
|
| 350 |
+
if self._active_count == 0:
|
| 351 |
+
self._wakeup()
|
| 352 |
+
|
| 353 |
+
async def start_serving(self):
|
| 354 |
+
self._start_serving()
|
| 355 |
+
# Skip one loop iteration so that all 'loop.add_reader'
|
| 356 |
+
# go through.
|
| 357 |
+
await tasks.sleep(0)
|
| 358 |
+
|
| 359 |
+
async def serve_forever(self):
|
| 360 |
+
if self._serving_forever_fut is not None:
|
| 361 |
+
raise RuntimeError(
|
| 362 |
+
f'server {self!r} is already being awaited on serve_forever()')
|
| 363 |
+
if self._sockets is None:
|
| 364 |
+
raise RuntimeError(f'server {self!r} is closed')
|
| 365 |
+
|
| 366 |
+
self._start_serving()
|
| 367 |
+
self._serving_forever_fut = self._loop.create_future()
|
| 368 |
+
|
| 369 |
+
try:
|
| 370 |
+
await self._serving_forever_fut
|
| 371 |
+
except exceptions.CancelledError:
|
| 372 |
+
try:
|
| 373 |
+
self.close()
|
| 374 |
+
await self.wait_closed()
|
| 375 |
+
finally:
|
| 376 |
+
raise
|
| 377 |
+
finally:
|
| 378 |
+
self._serving_forever_fut = None
|
| 379 |
+
|
| 380 |
+
async def wait_closed(self):
|
| 381 |
+
if self._sockets is None or self._waiters is None:
|
| 382 |
+
return
|
| 383 |
+
waiter = self._loop.create_future()
|
| 384 |
+
self._waiters.append(waiter)
|
| 385 |
+
await waiter
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
class BaseEventLoop(events.AbstractEventLoop):
|
| 389 |
+
|
| 390 |
+
def __init__(self):
|
| 391 |
+
self._timer_cancelled_count = 0
|
| 392 |
+
self._closed = False
|
| 393 |
+
self._stopping = False
|
| 394 |
+
self._ready = collections.deque()
|
| 395 |
+
self._scheduled = []
|
| 396 |
+
self._default_executor = None
|
| 397 |
+
self._internal_fds = 0
|
| 398 |
+
# Identifier of the thread running the event loop, or None if the
|
| 399 |
+
# event loop is not running
|
| 400 |
+
self._thread_id = None
|
| 401 |
+
self._clock_resolution = time.get_clock_info('monotonic').resolution
|
| 402 |
+
self._exception_handler = None
|
| 403 |
+
self.set_debug(coroutines._is_debug_mode())
|
| 404 |
+
# In debug mode, if the execution of a callback or a step of a task
|
| 405 |
+
# exceed this duration in seconds, the slow callback/task is logged.
|
| 406 |
+
self.slow_callback_duration = 0.1
|
| 407 |
+
self._current_handle = None
|
| 408 |
+
self._task_factory = None
|
| 409 |
+
self._coroutine_origin_tracking_enabled = False
|
| 410 |
+
self._coroutine_origin_tracking_saved_depth = None
|
| 411 |
+
|
| 412 |
+
# A weak set of all asynchronous generators that are
|
| 413 |
+
# being iterated by the loop.
|
| 414 |
+
self._asyncgens = weakref.WeakSet()
|
| 415 |
+
# Set to True when `loop.shutdown_asyncgens` is called.
|
| 416 |
+
self._asyncgens_shutdown_called = False
|
| 417 |
+
# Set to True when `loop.shutdown_default_executor` is called.
|
| 418 |
+
self._executor_shutdown_called = False
|
| 419 |
+
|
| 420 |
+
def __repr__(self):
|
| 421 |
+
return (
|
| 422 |
+
f'<{self.__class__.__name__} running={self.is_running()} '
|
| 423 |
+
f'closed={self.is_closed()} debug={self.get_debug()}>'
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
def create_future(self):
|
| 427 |
+
"""Create a Future object attached to the loop."""
|
| 428 |
+
return futures.Future(loop=self)
|
| 429 |
+
|
| 430 |
+
def create_task(self, coro, *, name=None, context=None):
|
| 431 |
+
"""Schedule a coroutine object.
|
| 432 |
+
|
| 433 |
+
Return a task object.
|
| 434 |
+
"""
|
| 435 |
+
self._check_closed()
|
| 436 |
+
if self._task_factory is None:
|
| 437 |
+
task = tasks.Task(coro, loop=self, name=name, context=context)
|
| 438 |
+
if task._source_traceback:
|
| 439 |
+
del task._source_traceback[-1]
|
| 440 |
+
else:
|
| 441 |
+
if context is None:
|
| 442 |
+
# Use legacy API if context is not needed
|
| 443 |
+
task = self._task_factory(self, coro)
|
| 444 |
+
else:
|
| 445 |
+
task = self._task_factory(self, coro, context=context)
|
| 446 |
+
|
| 447 |
+
tasks._set_task_name(task, name)
|
| 448 |
+
|
| 449 |
+
return task
|
| 450 |
+
|
| 451 |
+
def set_task_factory(self, factory):
|
| 452 |
+
"""Set a task factory that will be used by loop.create_task().
|
| 453 |
+
|
| 454 |
+
If factory is None the default task factory will be set.
|
| 455 |
+
|
| 456 |
+
If factory is a callable, it should have a signature matching
|
| 457 |
+
'(loop, coro)', where 'loop' will be a reference to the active
|
| 458 |
+
event loop, 'coro' will be a coroutine object. The callable
|
| 459 |
+
must return a Future.
|
| 460 |
+
"""
|
| 461 |
+
if factory is not None and not callable(factory):
|
| 462 |
+
raise TypeError('task factory must be a callable or None')
|
| 463 |
+
self._task_factory = factory
|
| 464 |
+
|
| 465 |
+
def get_task_factory(self):
|
| 466 |
+
"""Return a task factory, or None if the default one is in use."""
|
| 467 |
+
return self._task_factory
|
| 468 |
+
|
| 469 |
+
def _make_socket_transport(self, sock, protocol, waiter=None, *,
|
| 470 |
+
extra=None, server=None):
|
| 471 |
+
"""Create socket transport."""
|
| 472 |
+
raise NotImplementedError
|
| 473 |
+
|
| 474 |
+
def _make_ssl_transport(
|
| 475 |
+
self, rawsock, protocol, sslcontext, waiter=None,
|
| 476 |
+
*, server_side=False, server_hostname=None,
|
| 477 |
+
extra=None, server=None,
|
| 478 |
+
ssl_handshake_timeout=None,
|
| 479 |
+
ssl_shutdown_timeout=None,
|
| 480 |
+
call_connection_made=True):
|
| 481 |
+
"""Create SSL transport."""
|
| 482 |
+
raise NotImplementedError
|
| 483 |
+
|
| 484 |
+
def _make_datagram_transport(self, sock, protocol,
|
| 485 |
+
address=None, waiter=None, extra=None):
|
| 486 |
+
"""Create datagram transport."""
|
| 487 |
+
raise NotImplementedError
|
| 488 |
+
|
| 489 |
+
def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
|
| 490 |
+
extra=None):
|
| 491 |
+
"""Create read pipe transport."""
|
| 492 |
+
raise NotImplementedError
|
| 493 |
+
|
| 494 |
+
def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
|
| 495 |
+
extra=None):
|
| 496 |
+
"""Create write pipe transport."""
|
| 497 |
+
raise NotImplementedError
|
| 498 |
+
|
| 499 |
+
async def _make_subprocess_transport(self, protocol, args, shell,
|
| 500 |
+
stdin, stdout, stderr, bufsize,
|
| 501 |
+
extra=None, **kwargs):
|
| 502 |
+
"""Create subprocess transport."""
|
| 503 |
+
raise NotImplementedError
|
| 504 |
+
|
| 505 |
+
def _write_to_self(self):
|
| 506 |
+
"""Write a byte to self-pipe, to wake up the event loop.
|
| 507 |
+
|
| 508 |
+
This may be called from a different thread.
|
| 509 |
+
|
| 510 |
+
The subclass is responsible for implementing the self-pipe.
|
| 511 |
+
"""
|
| 512 |
+
raise NotImplementedError
|
| 513 |
+
|
| 514 |
+
def _process_events(self, event_list):
|
| 515 |
+
"""Process selector events."""
|
| 516 |
+
raise NotImplementedError
|
| 517 |
+
|
| 518 |
+
def _check_closed(self):
|
| 519 |
+
if self._closed:
|
| 520 |
+
raise RuntimeError('Event loop is closed')
|
| 521 |
+
|
| 522 |
+
def _check_default_executor(self):
|
| 523 |
+
if self._executor_shutdown_called:
|
| 524 |
+
raise RuntimeError('Executor shutdown has been called')
|
| 525 |
+
|
| 526 |
+
def _asyncgen_finalizer_hook(self, agen):
|
| 527 |
+
self._asyncgens.discard(agen)
|
| 528 |
+
if not self.is_closed():
|
| 529 |
+
self.call_soon_threadsafe(self.create_task, agen.aclose())
|
| 530 |
+
|
| 531 |
+
def _asyncgen_firstiter_hook(self, agen):
|
| 532 |
+
if self._asyncgens_shutdown_called:
|
| 533 |
+
warnings.warn(
|
| 534 |
+
f"asynchronous generator {agen!r} was scheduled after "
|
| 535 |
+
f"loop.shutdown_asyncgens() call",
|
| 536 |
+
ResourceWarning, source=self)
|
| 537 |
+
|
| 538 |
+
self._asyncgens.add(agen)
|
| 539 |
+
|
| 540 |
+
async def shutdown_asyncgens(self):
|
| 541 |
+
"""Shutdown all active asynchronous generators."""
|
| 542 |
+
self._asyncgens_shutdown_called = True
|
| 543 |
+
|
| 544 |
+
if not len(self._asyncgens):
|
| 545 |
+
# If Python version is <3.6 or we don't have any asynchronous
|
| 546 |
+
# generators alive.
|
| 547 |
+
return
|
| 548 |
+
|
| 549 |
+
closing_agens = list(self._asyncgens)
|
| 550 |
+
self._asyncgens.clear()
|
| 551 |
+
|
| 552 |
+
results = await tasks.gather(
|
| 553 |
+
*[ag.aclose() for ag in closing_agens],
|
| 554 |
+
return_exceptions=True)
|
| 555 |
+
|
| 556 |
+
for result, agen in zip(results, closing_agens):
|
| 557 |
+
if isinstance(result, Exception):
|
| 558 |
+
self.call_exception_handler({
|
| 559 |
+
'message': f'an error occurred during closing of '
|
| 560 |
+
f'asynchronous generator {agen!r}',
|
| 561 |
+
'exception': result,
|
| 562 |
+
'asyncgen': agen
|
| 563 |
+
})
|
| 564 |
+
|
| 565 |
+
async def shutdown_default_executor(self):
|
| 566 |
+
"""Schedule the shutdown of the default executor."""
|
| 567 |
+
self._executor_shutdown_called = True
|
| 568 |
+
if self._default_executor is None:
|
| 569 |
+
return
|
| 570 |
+
future = self.create_future()
|
| 571 |
+
thread = threading.Thread(target=self._do_shutdown, args=(future,))
|
| 572 |
+
thread.start()
|
| 573 |
+
try:
|
| 574 |
+
await future
|
| 575 |
+
finally:
|
| 576 |
+
thread.join()
|
| 577 |
+
|
| 578 |
+
def _do_shutdown(self, future):
|
| 579 |
+
try:
|
| 580 |
+
self._default_executor.shutdown(wait=True)
|
| 581 |
+
if not self.is_closed():
|
| 582 |
+
self.call_soon_threadsafe(future.set_result, None)
|
| 583 |
+
except Exception as ex:
|
| 584 |
+
if not self.is_closed():
|
| 585 |
+
self.call_soon_threadsafe(future.set_exception, ex)
|
| 586 |
+
|
| 587 |
+
def _check_running(self):
|
| 588 |
+
if self.is_running():
|
| 589 |
+
raise RuntimeError('This event loop is already running')
|
| 590 |
+
if events._get_running_loop() is not None:
|
| 591 |
+
raise RuntimeError(
|
| 592 |
+
'Cannot run the event loop while another loop is running')
|
| 593 |
+
|
| 594 |
+
def run_forever(self):
|
| 595 |
+
"""Run until stop() is called."""
|
| 596 |
+
self._check_closed()
|
| 597 |
+
self._check_running()
|
| 598 |
+
self._set_coroutine_origin_tracking(self._debug)
|
| 599 |
+
|
| 600 |
+
old_agen_hooks = sys.get_asyncgen_hooks()
|
| 601 |
+
try:
|
| 602 |
+
self._thread_id = threading.get_ident()
|
| 603 |
+
sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
|
| 604 |
+
finalizer=self._asyncgen_finalizer_hook)
|
| 605 |
+
|
| 606 |
+
events._set_running_loop(self)
|
| 607 |
+
while True:
|
| 608 |
+
self._run_once()
|
| 609 |
+
if self._stopping:
|
| 610 |
+
break
|
| 611 |
+
finally:
|
| 612 |
+
self._stopping = False
|
| 613 |
+
self._thread_id = None
|
| 614 |
+
events._set_running_loop(None)
|
| 615 |
+
self._set_coroutine_origin_tracking(False)
|
| 616 |
+
sys.set_asyncgen_hooks(*old_agen_hooks)
|
| 617 |
+
|
| 618 |
+
def run_until_complete(self, future):
|
| 619 |
+
"""Run until the Future is done.
|
| 620 |
+
|
| 621 |
+
If the argument is a coroutine, it is wrapped in a Task.
|
| 622 |
+
|
| 623 |
+
WARNING: It would be disastrous to call run_until_complete()
|
| 624 |
+
with the same coroutine twice -- it would wrap it in two
|
| 625 |
+
different Tasks and that can't be good.
|
| 626 |
+
|
| 627 |
+
Return the Future's result, or raise its exception.
|
| 628 |
+
"""
|
| 629 |
+
self._check_closed()
|
| 630 |
+
self._check_running()
|
| 631 |
+
|
| 632 |
+
new_task = not futures.isfuture(future)
|
| 633 |
+
future = tasks.ensure_future(future, loop=self)
|
| 634 |
+
if new_task:
|
| 635 |
+
# An exception is raised if the future didn't complete, so there
|
| 636 |
+
# is no need to log the "destroy pending task" message
|
| 637 |
+
future._log_destroy_pending = False
|
| 638 |
+
|
| 639 |
+
future.add_done_callback(_run_until_complete_cb)
|
| 640 |
+
try:
|
| 641 |
+
self.run_forever()
|
| 642 |
+
except:
|
| 643 |
+
if new_task and future.done() and not future.cancelled():
|
| 644 |
+
# The coroutine raised a BaseException. Consume the exception
|
| 645 |
+
# to not log a warning, the caller doesn't have access to the
|
| 646 |
+
# local task.
|
| 647 |
+
future.exception()
|
| 648 |
+
raise
|
| 649 |
+
finally:
|
| 650 |
+
future.remove_done_callback(_run_until_complete_cb)
|
| 651 |
+
if not future.done():
|
| 652 |
+
raise RuntimeError('Event loop stopped before Future completed.')
|
| 653 |
+
|
| 654 |
+
return future.result()
|
| 655 |
+
|
| 656 |
+
def stop(self):
|
| 657 |
+
"""Stop running the event loop.
|
| 658 |
+
|
| 659 |
+
Every callback already scheduled will still run. This simply informs
|
| 660 |
+
run_forever to stop looping after a complete iteration.
|
| 661 |
+
"""
|
| 662 |
+
self._stopping = True
|
| 663 |
+
|
| 664 |
+
def close(self):
|
| 665 |
+
"""Close the event loop.
|
| 666 |
+
|
| 667 |
+
This clears the queues and shuts down the executor,
|
| 668 |
+
but does not wait for the executor to finish.
|
| 669 |
+
|
| 670 |
+
The event loop must not be running.
|
| 671 |
+
"""
|
| 672 |
+
if self.is_running():
|
| 673 |
+
raise RuntimeError("Cannot close a running event loop")
|
| 674 |
+
if self._closed:
|
| 675 |
+
return
|
| 676 |
+
if self._debug:
|
| 677 |
+
logger.debug("Close %r", self)
|
| 678 |
+
self._closed = True
|
| 679 |
+
self._ready.clear()
|
| 680 |
+
self._scheduled.clear()
|
| 681 |
+
self._executor_shutdown_called = True
|
| 682 |
+
executor = self._default_executor
|
| 683 |
+
if executor is not None:
|
| 684 |
+
self._default_executor = None
|
| 685 |
+
executor.shutdown(wait=False)
|
| 686 |
+
|
| 687 |
+
def is_closed(self):
|
| 688 |
+
"""Returns True if the event loop was closed."""
|
| 689 |
+
return self._closed
|
| 690 |
+
|
| 691 |
+
def __del__(self, _warn=warnings.warn):
|
| 692 |
+
if not self.is_closed():
|
| 693 |
+
_warn(f"unclosed event loop {self!r}", ResourceWarning, source=self)
|
| 694 |
+
if not self.is_running():
|
| 695 |
+
self.close()
|
| 696 |
+
|
| 697 |
+
def is_running(self):
|
| 698 |
+
"""Returns True if the event loop is running."""
|
| 699 |
+
return (self._thread_id is not None)
|
| 700 |
+
|
| 701 |
+
def time(self):
|
| 702 |
+
"""Return the time according to the event loop's clock.
|
| 703 |
+
|
| 704 |
+
This is a float expressed in seconds since an epoch, but the
|
| 705 |
+
epoch, precision, accuracy and drift are unspecified and may
|
| 706 |
+
differ per event loop.
|
| 707 |
+
"""
|
| 708 |
+
return time.monotonic()
|
| 709 |
+
|
| 710 |
+
def call_later(self, delay, callback, *args, context=None):
|
| 711 |
+
"""Arrange for a callback to be called at a given time.
|
| 712 |
+
|
| 713 |
+
Return a Handle: an opaque object with a cancel() method that
|
| 714 |
+
can be used to cancel the call.
|
| 715 |
+
|
| 716 |
+
The delay can be an int or float, expressed in seconds. It is
|
| 717 |
+
always relative to the current time.
|
| 718 |
+
|
| 719 |
+
Each callback will be called exactly once. If two callbacks
|
| 720 |
+
are scheduled for exactly the same time, it is undefined which
|
| 721 |
+
will be called first.
|
| 722 |
+
|
| 723 |
+
Any positional arguments after the callback will be passed to
|
| 724 |
+
the callback when it is called.
|
| 725 |
+
"""
|
| 726 |
+
if delay is None:
|
| 727 |
+
raise TypeError('delay must not be None')
|
| 728 |
+
timer = self.call_at(self.time() + delay, callback, *args,
|
| 729 |
+
context=context)
|
| 730 |
+
if timer._source_traceback:
|
| 731 |
+
del timer._source_traceback[-1]
|
| 732 |
+
return timer
|
| 733 |
+
|
| 734 |
+
def call_at(self, when, callback, *args, context=None):
|
| 735 |
+
"""Like call_later(), but uses an absolute time.
|
| 736 |
+
|
| 737 |
+
Absolute time corresponds to the event loop's time() method.
|
| 738 |
+
"""
|
| 739 |
+
if when is None:
|
| 740 |
+
raise TypeError("when cannot be None")
|
| 741 |
+
self._check_closed()
|
| 742 |
+
if self._debug:
|
| 743 |
+
self._check_thread()
|
| 744 |
+
self._check_callback(callback, 'call_at')
|
| 745 |
+
timer = events.TimerHandle(when, callback, args, self, context)
|
| 746 |
+
if timer._source_traceback:
|
| 747 |
+
del timer._source_traceback[-1]
|
| 748 |
+
heapq.heappush(self._scheduled, timer)
|
| 749 |
+
timer._scheduled = True
|
| 750 |
+
return timer
|
| 751 |
+
|
| 752 |
+
def call_soon(self, callback, *args, context=None):
|
| 753 |
+
"""Arrange for a callback to be called as soon as possible.
|
| 754 |
+
|
| 755 |
+
This operates as a FIFO queue: callbacks are called in the
|
| 756 |
+
order in which they are registered. Each callback will be
|
| 757 |
+
called exactly once.
|
| 758 |
+
|
| 759 |
+
Any positional arguments after the callback will be passed to
|
| 760 |
+
the callback when it is called.
|
| 761 |
+
"""
|
| 762 |
+
self._check_closed()
|
| 763 |
+
if self._debug:
|
| 764 |
+
self._check_thread()
|
| 765 |
+
self._check_callback(callback, 'call_soon')
|
| 766 |
+
handle = self._call_soon(callback, args, context)
|
| 767 |
+
if handle._source_traceback:
|
| 768 |
+
del handle._source_traceback[-1]
|
| 769 |
+
return handle
|
| 770 |
+
|
| 771 |
+
def _check_callback(self, callback, method):
|
| 772 |
+
if (coroutines.iscoroutine(callback) or
|
| 773 |
+
coroutines.iscoroutinefunction(callback)):
|
| 774 |
+
raise TypeError(
|
| 775 |
+
f"coroutines cannot be used with {method}()")
|
| 776 |
+
if not callable(callback):
|
| 777 |
+
raise TypeError(
|
| 778 |
+
f'a callable object was expected by {method}(), '
|
| 779 |
+
f'got {callback!r}')
|
| 780 |
+
|
| 781 |
+
def _call_soon(self, callback, args, context):
|
| 782 |
+
handle = events.Handle(callback, args, self, context)
|
| 783 |
+
if handle._source_traceback:
|
| 784 |
+
del handle._source_traceback[-1]
|
| 785 |
+
self._ready.append(handle)
|
| 786 |
+
return handle
|
| 787 |
+
|
| 788 |
+
def _check_thread(self):
|
| 789 |
+
"""Check that the current thread is the thread running the event loop.
|
| 790 |
+
|
| 791 |
+
Non-thread-safe methods of this class make this assumption and will
|
| 792 |
+
likely behave incorrectly when the assumption is violated.
|
| 793 |
+
|
| 794 |
+
Should only be called when (self._debug == True). The caller is
|
| 795 |
+
responsible for checking this condition for performance reasons.
|
| 796 |
+
"""
|
| 797 |
+
if self._thread_id is None:
|
| 798 |
+
return
|
| 799 |
+
thread_id = threading.get_ident()
|
| 800 |
+
if thread_id != self._thread_id:
|
| 801 |
+
raise RuntimeError(
|
| 802 |
+
"Non-thread-safe operation invoked on an event loop other "
|
| 803 |
+
"than the current one")
|
| 804 |
+
|
| 805 |
+
def call_soon_threadsafe(self, callback, *args, context=None):
|
| 806 |
+
"""Like call_soon(), but thread-safe."""
|
| 807 |
+
self._check_closed()
|
| 808 |
+
if self._debug:
|
| 809 |
+
self._check_callback(callback, 'call_soon_threadsafe')
|
| 810 |
+
handle = self._call_soon(callback, args, context)
|
| 811 |
+
if handle._source_traceback:
|
| 812 |
+
del handle._source_traceback[-1]
|
| 813 |
+
self._write_to_self()
|
| 814 |
+
return handle
|
| 815 |
+
|
| 816 |
+
def run_in_executor(self, executor, func, *args):
|
| 817 |
+
self._check_closed()
|
| 818 |
+
if self._debug:
|
| 819 |
+
self._check_callback(func, 'run_in_executor')
|
| 820 |
+
if executor is None:
|
| 821 |
+
executor = self._default_executor
|
| 822 |
+
# Only check when the default executor is being used
|
| 823 |
+
self._check_default_executor()
|
| 824 |
+
if executor is None:
|
| 825 |
+
executor = concurrent.futures.ThreadPoolExecutor(
|
| 826 |
+
thread_name_prefix='asyncio'
|
| 827 |
+
)
|
| 828 |
+
self._default_executor = executor
|
| 829 |
+
return futures.wrap_future(
|
| 830 |
+
executor.submit(func, *args), loop=self)
|
| 831 |
+
|
| 832 |
+
def set_default_executor(self, executor):
|
| 833 |
+
if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
|
| 834 |
+
raise TypeError('executor must be ThreadPoolExecutor instance')
|
| 835 |
+
self._default_executor = executor
|
| 836 |
+
|
| 837 |
+
def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
|
| 838 |
+
msg = [f"{host}:{port!r}"]
|
| 839 |
+
if family:
|
| 840 |
+
msg.append(f'family={family!r}')
|
| 841 |
+
if type:
|
| 842 |
+
msg.append(f'type={type!r}')
|
| 843 |
+
if proto:
|
| 844 |
+
msg.append(f'proto={proto!r}')
|
| 845 |
+
if flags:
|
| 846 |
+
msg.append(f'flags={flags!r}')
|
| 847 |
+
msg = ', '.join(msg)
|
| 848 |
+
logger.debug('Get address info %s', msg)
|
| 849 |
+
|
| 850 |
+
t0 = self.time()
|
| 851 |
+
addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
|
| 852 |
+
dt = self.time() - t0
|
| 853 |
+
|
| 854 |
+
msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
|
| 855 |
+
if dt >= self.slow_callback_duration:
|
| 856 |
+
logger.info(msg)
|
| 857 |
+
else:
|
| 858 |
+
logger.debug(msg)
|
| 859 |
+
return addrinfo
|
| 860 |
+
|
| 861 |
+
async def getaddrinfo(self, host, port, *,
|
| 862 |
+
family=0, type=0, proto=0, flags=0):
|
| 863 |
+
if self._debug:
|
| 864 |
+
getaddr_func = self._getaddrinfo_debug
|
| 865 |
+
else:
|
| 866 |
+
getaddr_func = socket.getaddrinfo
|
| 867 |
+
|
| 868 |
+
return await self.run_in_executor(
|
| 869 |
+
None, getaddr_func, host, port, family, type, proto, flags)
|
| 870 |
+
|
| 871 |
+
async def getnameinfo(self, sockaddr, flags=0):
|
| 872 |
+
return await self.run_in_executor(
|
| 873 |
+
None, socket.getnameinfo, sockaddr, flags)
|
| 874 |
+
|
| 875 |
+
async def sock_sendfile(self, sock, file, offset=0, count=None,
|
| 876 |
+
*, fallback=True):
|
| 877 |
+
if self._debug and sock.gettimeout() != 0:
|
| 878 |
+
raise ValueError("the socket must be non-blocking")
|
| 879 |
+
_check_ssl_socket(sock)
|
| 880 |
+
self._check_sendfile_params(sock, file, offset, count)
|
| 881 |
+
try:
|
| 882 |
+
return await self._sock_sendfile_native(sock, file,
|
| 883 |
+
offset, count)
|
| 884 |
+
except exceptions.SendfileNotAvailableError as exc:
|
| 885 |
+
if not fallback:
|
| 886 |
+
raise
|
| 887 |
+
return await self._sock_sendfile_fallback(sock, file,
|
| 888 |
+
offset, count)
|
| 889 |
+
|
| 890 |
+
async def _sock_sendfile_native(self, sock, file, offset, count):
|
| 891 |
+
# NB: sendfile syscall is not supported for SSL sockets and
|
| 892 |
+
# non-mmap files even if sendfile is supported by OS
|
| 893 |
+
raise exceptions.SendfileNotAvailableError(
|
| 894 |
+
f"syscall sendfile is not available for socket {sock!r} "
|
| 895 |
+
f"and file {file!r} combination")
|
| 896 |
+
|
| 897 |
+
async def _sock_sendfile_fallback(self, sock, file, offset, count):
|
| 898 |
+
if offset:
|
| 899 |
+
file.seek(offset)
|
| 900 |
+
blocksize = (
|
| 901 |
+
min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
|
| 902 |
+
if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
|
| 903 |
+
)
|
| 904 |
+
buf = bytearray(blocksize)
|
| 905 |
+
total_sent = 0
|
| 906 |
+
try:
|
| 907 |
+
while True:
|
| 908 |
+
if count:
|
| 909 |
+
blocksize = min(count - total_sent, blocksize)
|
| 910 |
+
if blocksize <= 0:
|
| 911 |
+
break
|
| 912 |
+
view = memoryview(buf)[:blocksize]
|
| 913 |
+
read = await self.run_in_executor(None, file.readinto, view)
|
| 914 |
+
if not read:
|
| 915 |
+
break # EOF
|
| 916 |
+
await self.sock_sendall(sock, view[:read])
|
| 917 |
+
total_sent += read
|
| 918 |
+
return total_sent
|
| 919 |
+
finally:
|
| 920 |
+
if total_sent > 0 and hasattr(file, 'seek'):
|
| 921 |
+
file.seek(offset + total_sent)
|
| 922 |
+
|
| 923 |
+
def _check_sendfile_params(self, sock, file, offset, count):
|
| 924 |
+
if 'b' not in getattr(file, 'mode', 'b'):
|
| 925 |
+
raise ValueError("file should be opened in binary mode")
|
| 926 |
+
if not sock.type == socket.SOCK_STREAM:
|
| 927 |
+
raise ValueError("only SOCK_STREAM type sockets are supported")
|
| 928 |
+
if count is not None:
|
| 929 |
+
if not isinstance(count, int):
|
| 930 |
+
raise TypeError(
|
| 931 |
+
"count must be a positive integer (got {!r})".format(count))
|
| 932 |
+
if count <= 0:
|
| 933 |
+
raise ValueError(
|
| 934 |
+
"count must be a positive integer (got {!r})".format(count))
|
| 935 |
+
if not isinstance(offset, int):
|
| 936 |
+
raise TypeError(
|
| 937 |
+
"offset must be a non-negative integer (got {!r})".format(
|
| 938 |
+
offset))
|
| 939 |
+
if offset < 0:
|
| 940 |
+
raise ValueError(
|
| 941 |
+
"offset must be a non-negative integer (got {!r})".format(
|
| 942 |
+
offset))
|
| 943 |
+
|
| 944 |
+
async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
|
| 945 |
+
"""Create, bind and connect one socket."""
|
| 946 |
+
my_exceptions = []
|
| 947 |
+
exceptions.append(my_exceptions)
|
| 948 |
+
family, type_, proto, _, address = addr_info
|
| 949 |
+
sock = None
|
| 950 |
+
try:
|
| 951 |
+
sock = socket.socket(family=family, type=type_, proto=proto)
|
| 952 |
+
sock.setblocking(False)
|
| 953 |
+
if local_addr_infos is not None:
|
| 954 |
+
for lfamily, _, _, _, laddr in local_addr_infos:
|
| 955 |
+
# skip local addresses of different family
|
| 956 |
+
if lfamily != family:
|
| 957 |
+
continue
|
| 958 |
+
try:
|
| 959 |
+
sock.bind(laddr)
|
| 960 |
+
break
|
| 961 |
+
except OSError as exc:
|
| 962 |
+
msg = (
|
| 963 |
+
f'error while attempting to bind on '
|
| 964 |
+
f'address {laddr!r}: '
|
| 965 |
+
f'{exc.strerror.lower()}'
|
| 966 |
+
)
|
| 967 |
+
exc = OSError(exc.errno, msg)
|
| 968 |
+
my_exceptions.append(exc)
|
| 969 |
+
else: # all bind attempts failed
|
| 970 |
+
if my_exceptions:
|
| 971 |
+
raise my_exceptions.pop()
|
| 972 |
+
else:
|
| 973 |
+
raise OSError(f"no matching local address with {family=} found")
|
| 974 |
+
await self.sock_connect(sock, address)
|
| 975 |
+
return sock
|
| 976 |
+
except OSError as exc:
|
| 977 |
+
my_exceptions.append(exc)
|
| 978 |
+
if sock is not None:
|
| 979 |
+
sock.close()
|
| 980 |
+
raise
|
| 981 |
+
except:
|
| 982 |
+
if sock is not None:
|
| 983 |
+
sock.close()
|
| 984 |
+
raise
|
| 985 |
+
finally:
|
| 986 |
+
exceptions = my_exceptions = None
|
| 987 |
+
|
| 988 |
+
async def create_connection(
|
| 989 |
+
self, protocol_factory, host=None, port=None,
|
| 990 |
+
*, ssl=None, family=0,
|
| 991 |
+
proto=0, flags=0, sock=None,
|
| 992 |
+
local_addr=None, server_hostname=None,
|
| 993 |
+
ssl_handshake_timeout=None,
|
| 994 |
+
ssl_shutdown_timeout=None,
|
| 995 |
+
happy_eyeballs_delay=None, interleave=None):
|
| 996 |
+
"""Connect to a TCP server.
|
| 997 |
+
|
| 998 |
+
Create a streaming transport connection to a given internet host and
|
| 999 |
+
port: socket family AF_INET or socket.AF_INET6 depending on host (or
|
| 1000 |
+
family if specified), socket type SOCK_STREAM. protocol_factory must be
|
| 1001 |
+
a callable returning a protocol instance.
|
| 1002 |
+
|
| 1003 |
+
This method is a coroutine which will try to establish the connection
|
| 1004 |
+
in the background. When successful, the coroutine returns a
|
| 1005 |
+
(transport, protocol) pair.
|
| 1006 |
+
"""
|
| 1007 |
+
if server_hostname is not None and not ssl:
|
| 1008 |
+
raise ValueError('server_hostname is only meaningful with ssl')
|
| 1009 |
+
|
| 1010 |
+
if server_hostname is None and ssl:
|
| 1011 |
+
# Use host as default for server_hostname. It is an error
|
| 1012 |
+
# if host is empty or not set, e.g. when an
|
| 1013 |
+
# already-connected socket was passed or when only a port
|
| 1014 |
+
# is given. To avoid this error, you can pass
|
| 1015 |
+
# server_hostname='' -- this will bypass the hostname
|
| 1016 |
+
# check. (This also means that if host is a numeric
|
| 1017 |
+
# IP/IPv6 address, we will attempt to verify that exact
|
| 1018 |
+
# address; this will probably fail, but it is possible to
|
| 1019 |
+
# create a certificate for a specific IP address, so we
|
| 1020 |
+
# don't judge it here.)
|
| 1021 |
+
if not host:
|
| 1022 |
+
raise ValueError('You must set server_hostname '
|
| 1023 |
+
'when using ssl without a host')
|
| 1024 |
+
server_hostname = host
|
| 1025 |
+
|
| 1026 |
+
if ssl_handshake_timeout is not None and not ssl:
|
| 1027 |
+
raise ValueError(
|
| 1028 |
+
'ssl_handshake_timeout is only meaningful with ssl')
|
| 1029 |
+
|
| 1030 |
+
if ssl_shutdown_timeout is not None and not ssl:
|
| 1031 |
+
raise ValueError(
|
| 1032 |
+
'ssl_shutdown_timeout is only meaningful with ssl')
|
| 1033 |
+
|
| 1034 |
+
if sock is not None:
|
| 1035 |
+
_check_ssl_socket(sock)
|
| 1036 |
+
|
| 1037 |
+
if happy_eyeballs_delay is not None and interleave is None:
|
| 1038 |
+
# If using happy eyeballs, default to interleave addresses by family
|
| 1039 |
+
interleave = 1
|
| 1040 |
+
|
| 1041 |
+
if host is not None or port is not None:
|
| 1042 |
+
if sock is not None:
|
| 1043 |
+
raise ValueError(
|
| 1044 |
+
'host/port and sock can not be specified at the same time')
|
| 1045 |
+
|
| 1046 |
+
infos = await self._ensure_resolved(
|
| 1047 |
+
(host, port), family=family,
|
| 1048 |
+
type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
|
| 1049 |
+
if not infos:
|
| 1050 |
+
raise OSError('getaddrinfo() returned empty list')
|
| 1051 |
+
|
| 1052 |
+
if local_addr is not None:
|
| 1053 |
+
laddr_infos = await self._ensure_resolved(
|
| 1054 |
+
local_addr, family=family,
|
| 1055 |
+
type=socket.SOCK_STREAM, proto=proto,
|
| 1056 |
+
flags=flags, loop=self)
|
| 1057 |
+
if not laddr_infos:
|
| 1058 |
+
raise OSError('getaddrinfo() returned empty list')
|
| 1059 |
+
else:
|
| 1060 |
+
laddr_infos = None
|
| 1061 |
+
|
| 1062 |
+
if interleave:
|
| 1063 |
+
infos = _interleave_addrinfos(infos, interleave)
|
| 1064 |
+
|
| 1065 |
+
exceptions = []
|
| 1066 |
+
if happy_eyeballs_delay is None:
|
| 1067 |
+
# not using happy eyeballs
|
| 1068 |
+
for addrinfo in infos:
|
| 1069 |
+
try:
|
| 1070 |
+
sock = await self._connect_sock(
|
| 1071 |
+
exceptions, addrinfo, laddr_infos)
|
| 1072 |
+
break
|
| 1073 |
+
except OSError:
|
| 1074 |
+
continue
|
| 1075 |
+
else: # using happy eyeballs
|
| 1076 |
+
sock, _, _ = await staggered.staggered_race(
|
| 1077 |
+
(functools.partial(self._connect_sock,
|
| 1078 |
+
exceptions, addrinfo, laddr_infos)
|
| 1079 |
+
for addrinfo in infos),
|
| 1080 |
+
happy_eyeballs_delay, loop=self)
|
| 1081 |
+
|
| 1082 |
+
if sock is None:
|
| 1083 |
+
exceptions = [exc for sub in exceptions for exc in sub]
|
| 1084 |
+
try:
|
| 1085 |
+
if len(exceptions) == 1:
|
| 1086 |
+
raise exceptions[0]
|
| 1087 |
+
else:
|
| 1088 |
+
# If they all have the same str(), raise one.
|
| 1089 |
+
model = str(exceptions[0])
|
| 1090 |
+
if all(str(exc) == model for exc in exceptions):
|
| 1091 |
+
raise exceptions[0]
|
| 1092 |
+
# Raise a combined exception so the user can see all
|
| 1093 |
+
# the various error messages.
|
| 1094 |
+
raise OSError('Multiple exceptions: {}'.format(
|
| 1095 |
+
', '.join(str(exc) for exc in exceptions)))
|
| 1096 |
+
finally:
|
| 1097 |
+
exceptions = None
|
| 1098 |
+
|
| 1099 |
+
else:
|
| 1100 |
+
if sock is None:
|
| 1101 |
+
raise ValueError(
|
| 1102 |
+
'host and port was not specified and no sock specified')
|
| 1103 |
+
if sock.type != socket.SOCK_STREAM:
|
| 1104 |
+
# We allow AF_INET, AF_INET6, AF_UNIX as long as they
|
| 1105 |
+
# are SOCK_STREAM.
|
| 1106 |
+
# We support passing AF_UNIX sockets even though we have
|
| 1107 |
+
# a dedicated API for that: create_unix_connection.
|
| 1108 |
+
# Disallowing AF_UNIX in this method, breaks backwards
|
| 1109 |
+
# compatibility.
|
| 1110 |
+
raise ValueError(
|
| 1111 |
+
f'A Stream Socket was expected, got {sock!r}')
|
| 1112 |
+
|
| 1113 |
+
transport, protocol = await self._create_connection_transport(
|
| 1114 |
+
sock, protocol_factory, ssl, server_hostname,
|
| 1115 |
+
ssl_handshake_timeout=ssl_handshake_timeout,
|
| 1116 |
+
ssl_shutdown_timeout=ssl_shutdown_timeout)
|
| 1117 |
+
if self._debug:
|
| 1118 |
+
# Get the socket from the transport because SSL transport closes
|
| 1119 |
+
# the old socket and creates a new SSL socket
|
| 1120 |
+
sock = transport.get_extra_info('socket')
|
| 1121 |
+
logger.debug("%r connected to %s:%r: (%r, %r)",
|
| 1122 |
+
sock, host, port, transport, protocol)
|
| 1123 |
+
return transport, protocol
|
| 1124 |
+
|
| 1125 |
+
async def _create_connection_transport(
|
| 1126 |
+
self, sock, protocol_factory, ssl,
|
| 1127 |
+
server_hostname, server_side=False,
|
| 1128 |
+
ssl_handshake_timeout=None,
|
| 1129 |
+
ssl_shutdown_timeout=None):
|
| 1130 |
+
|
| 1131 |
+
sock.setblocking(False)
|
| 1132 |
+
|
| 1133 |
+
protocol = protocol_factory()
|
| 1134 |
+
waiter = self.create_future()
|
| 1135 |
+
if ssl:
|
| 1136 |
+
sslcontext = None if isinstance(ssl, bool) else ssl
|
| 1137 |
+
transport = self._make_ssl_transport(
|
| 1138 |
+
sock, protocol, sslcontext, waiter,
|
| 1139 |
+
server_side=server_side, server_hostname=server_hostname,
|
| 1140 |
+
ssl_handshake_timeout=ssl_handshake_timeout,
|
| 1141 |
+
ssl_shutdown_timeout=ssl_shutdown_timeout)
|
| 1142 |
+
else:
|
| 1143 |
+
transport = self._make_socket_transport(sock, protocol, waiter)
|
| 1144 |
+
|
| 1145 |
+
try:
|
| 1146 |
+
await waiter
|
| 1147 |
+
except:
|
| 1148 |
+
transport.close()
|
| 1149 |
+
raise
|
| 1150 |
+
|
| 1151 |
+
return transport, protocol
|
| 1152 |
+
|
| 1153 |
+
async def sendfile(self, transport, file, offset=0, count=None,
|
| 1154 |
+
*, fallback=True):
|
| 1155 |
+
"""Send a file to transport.
|
| 1156 |
+
|
| 1157 |
+
Return the total number of bytes which were sent.
|
| 1158 |
+
|
| 1159 |
+
The method uses high-performance os.sendfile if available.
|
| 1160 |
+
|
| 1161 |
+
file must be a regular file object opened in binary mode.
|
| 1162 |
+
|
| 1163 |
+
offset tells from where to start reading the file. If specified,
|
| 1164 |
+
count is the total number of bytes to transmit as opposed to
|
| 1165 |
+
sending the file until EOF is reached. File position is updated on
|
| 1166 |
+
return or also in case of error in which case file.tell()
|
| 1167 |
+
can be used to figure out the number of bytes
|
| 1168 |
+
which were sent.
|
| 1169 |
+
|
| 1170 |
+
fallback set to True makes asyncio to manually read and send
|
| 1171 |
+
the file when the platform does not support the sendfile syscall
|
| 1172 |
+
(e.g. Windows or SSL socket on Unix).
|
| 1173 |
+
|
| 1174 |
+
Raise SendfileNotAvailableError if the system does not support
|
| 1175 |
+
sendfile syscall and fallback is False.
|
| 1176 |
+
"""
|
| 1177 |
+
if transport.is_closing():
|
| 1178 |
+
raise RuntimeError("Transport is closing")
|
| 1179 |
+
mode = getattr(transport, '_sendfile_compatible',
|
| 1180 |
+
constants._SendfileMode.UNSUPPORTED)
|
| 1181 |
+
if mode is constants._SendfileMode.UNSUPPORTED:
|
| 1182 |
+
raise RuntimeError(
|
| 1183 |
+
f"sendfile is not supported for transport {transport!r}")
|
| 1184 |
+
if mode is constants._SendfileMode.TRY_NATIVE:
|
| 1185 |
+
try:
|
| 1186 |
+
return await self._sendfile_native(transport, file,
|
| 1187 |
+
offset, count)
|
| 1188 |
+
except exceptions.SendfileNotAvailableError as exc:
|
| 1189 |
+
if not fallback:
|
| 1190 |
+
raise
|
| 1191 |
+
|
| 1192 |
+
if not fallback:
|
| 1193 |
+
raise RuntimeError(
|
| 1194 |
+
f"fallback is disabled and native sendfile is not "
|
| 1195 |
+
f"supported for transport {transport!r}")
|
| 1196 |
+
|
| 1197 |
+
return await self._sendfile_fallback(transport, file,
|
| 1198 |
+
offset, count)
|
| 1199 |
+
|
| 1200 |
+
async def _sendfile_native(self, transp, file, offset, count):
|
| 1201 |
+
raise exceptions.SendfileNotAvailableError(
|
| 1202 |
+
"sendfile syscall is not supported")
|
| 1203 |
+
|
| 1204 |
+
async def _sendfile_fallback(self, transp, file, offset, count):
|
| 1205 |
+
if offset:
|
| 1206 |
+
file.seek(offset)
|
| 1207 |
+
blocksize = min(count, 16384) if count else 16384
|
| 1208 |
+
buf = bytearray(blocksize)
|
| 1209 |
+
total_sent = 0
|
| 1210 |
+
proto = _SendfileFallbackProtocol(transp)
|
| 1211 |
+
try:
|
| 1212 |
+
while True:
|
| 1213 |
+
if count:
|
| 1214 |
+
blocksize = min(count - total_sent, blocksize)
|
| 1215 |
+
if blocksize <= 0:
|
| 1216 |
+
return total_sent
|
| 1217 |
+
view = memoryview(buf)[:blocksize]
|
| 1218 |
+
read = await self.run_in_executor(None, file.readinto, view)
|
| 1219 |
+
if not read:
|
| 1220 |
+
return total_sent # EOF
|
| 1221 |
+
await proto.drain()
|
| 1222 |
+
transp.write(view[:read])
|
| 1223 |
+
total_sent += read
|
| 1224 |
+
finally:
|
| 1225 |
+
if total_sent > 0 and hasattr(file, 'seek'):
|
| 1226 |
+
file.seek(offset + total_sent)
|
| 1227 |
+
await proto.restore()
|
| 1228 |
+
|
| 1229 |
+
async def start_tls(self, transport, protocol, sslcontext, *,
|
| 1230 |
+
server_side=False,
|
| 1231 |
+
server_hostname=None,
|
| 1232 |
+
ssl_handshake_timeout=None,
|
| 1233 |
+
ssl_shutdown_timeout=None):
|
| 1234 |
+
"""Upgrade transport to TLS.
|
| 1235 |
+
|
| 1236 |
+
Return a new transport that *protocol* should start using
|
| 1237 |
+
immediately.
|
| 1238 |
+
"""
|
| 1239 |
+
if ssl is None:
|
| 1240 |
+
raise RuntimeError('Python ssl module is not available')
|
| 1241 |
+
|
| 1242 |
+
if not isinstance(sslcontext, ssl.SSLContext):
|
| 1243 |
+
raise TypeError(
|
| 1244 |
+
f'sslcontext is expected to be an instance of ssl.SSLContext, '
|
| 1245 |
+
f'got {sslcontext!r}')
|
| 1246 |
+
|
| 1247 |
+
if not getattr(transport, '_start_tls_compatible', False):
|
| 1248 |
+
raise TypeError(
|
| 1249 |
+
f'transport {transport!r} is not supported by start_tls()')
|
| 1250 |
+
|
| 1251 |
+
waiter = self.create_future()
|
| 1252 |
+
ssl_protocol = sslproto.SSLProtocol(
|
| 1253 |
+
self, protocol, sslcontext, waiter,
|
| 1254 |
+
server_side, server_hostname,
|
| 1255 |
+
ssl_handshake_timeout=ssl_handshake_timeout,
|
| 1256 |
+
ssl_shutdown_timeout=ssl_shutdown_timeout,
|
| 1257 |
+
call_connection_made=False)
|
| 1258 |
+
|
| 1259 |
+
# Pause early so that "ssl_protocol.data_received()" doesn't
|
| 1260 |
+
# have a chance to get called before "ssl_protocol.connection_made()".
|
| 1261 |
+
transport.pause_reading()
|
| 1262 |
+
|
| 1263 |
+
transport.set_protocol(ssl_protocol)
|
| 1264 |
+
conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
|
| 1265 |
+
resume_cb = self.call_soon(transport.resume_reading)
|
| 1266 |
+
|
| 1267 |
+
try:
|
| 1268 |
+
await waiter
|
| 1269 |
+
except BaseException:
|
| 1270 |
+
transport.close()
|
| 1271 |
+
conmade_cb.cancel()
|
| 1272 |
+
resume_cb.cancel()
|
| 1273 |
+
raise
|
| 1274 |
+
|
| 1275 |
+
return ssl_protocol._app_transport
|
| 1276 |
+
|
| 1277 |
+
async def create_datagram_endpoint(self, protocol_factory,
|
| 1278 |
+
local_addr=None, remote_addr=None, *,
|
| 1279 |
+
family=0, proto=0, flags=0,
|
| 1280 |
+
reuse_port=None,
|
| 1281 |
+
allow_broadcast=None, sock=None):
|
| 1282 |
+
"""Create datagram connection."""
|
| 1283 |
+
if sock is not None:
|
| 1284 |
+
if sock.type == socket.SOCK_STREAM:
|
| 1285 |
+
raise ValueError(
|
| 1286 |
+
f'A datagram socket was expected, got {sock!r}')
|
| 1287 |
+
if (local_addr or remote_addr or
|
| 1288 |
+
family or proto or flags or
|
| 1289 |
+
reuse_port or allow_broadcast):
|
| 1290 |
+
# show the problematic kwargs in exception msg
|
| 1291 |
+
opts = dict(local_addr=local_addr, remote_addr=remote_addr,
|
| 1292 |
+
family=family, proto=proto, flags=flags,
|
| 1293 |
+
reuse_port=reuse_port,
|
| 1294 |
+
allow_broadcast=allow_broadcast)
|
| 1295 |
+
problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
|
| 1296 |
+
raise ValueError(
|
| 1297 |
+
f'socket modifier keyword arguments can not be used '
|
| 1298 |
+
f'when sock is specified. ({problems})')
|
| 1299 |
+
sock.setblocking(False)
|
| 1300 |
+
r_addr = None
|
| 1301 |
+
else:
|
| 1302 |
+
if not (local_addr or remote_addr):
|
| 1303 |
+
if family == 0:
|
| 1304 |
+
raise ValueError('unexpected address family')
|
| 1305 |
+
addr_pairs_info = (((family, proto), (None, None)),)
|
| 1306 |
+
elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
|
| 1307 |
+
for addr in (local_addr, remote_addr):
|
| 1308 |
+
if addr is not None and not isinstance(addr, str):
|
| 1309 |
+
raise TypeError('string is expected')
|
| 1310 |
+
|
| 1311 |
+
if local_addr and local_addr[0] not in (0, '\x00'):
|
| 1312 |
+
try:
|
| 1313 |
+
if stat.S_ISSOCK(os.stat(local_addr).st_mode):
|
| 1314 |
+
os.remove(local_addr)
|
| 1315 |
+
except FileNotFoundError:
|
| 1316 |
+
pass
|
| 1317 |
+
except OSError as err:
|
| 1318 |
+
# Directory may have permissions only to create socket.
|
| 1319 |
+
logger.error('Unable to check or remove stale UNIX '
|
| 1320 |
+
'socket %r: %r',
|
| 1321 |
+
local_addr, err)
|
| 1322 |
+
|
| 1323 |
+
addr_pairs_info = (((family, proto),
|
| 1324 |
+
(local_addr, remote_addr)), )
|
| 1325 |
+
else:
|
| 1326 |
+
# join address by (family, protocol)
|
| 1327 |
+
addr_infos = {} # Using order preserving dict
|
| 1328 |
+
for idx, addr in ((0, local_addr), (1, remote_addr)):
|
| 1329 |
+
if addr is not None:
|
| 1330 |
+
if not (isinstance(addr, tuple) and len(addr) == 2):
|
| 1331 |
+
raise TypeError('2-tuple is expected')
|
| 1332 |
+
|
| 1333 |
+
infos = await self._ensure_resolved(
|
| 1334 |
+
addr, family=family, type=socket.SOCK_DGRAM,
|
| 1335 |
+
proto=proto, flags=flags, loop=self)
|
| 1336 |
+
if not infos:
|
| 1337 |
+
raise OSError('getaddrinfo() returned empty list')
|
| 1338 |
+
|
| 1339 |
+
for fam, _, pro, _, address in infos:
|
| 1340 |
+
key = (fam, pro)
|
| 1341 |
+
if key not in addr_infos:
|
| 1342 |
+
addr_infos[key] = [None, None]
|
| 1343 |
+
addr_infos[key][idx] = address
|
| 1344 |
+
|
| 1345 |
+
# each addr has to have info for each (family, proto) pair
|
| 1346 |
+
addr_pairs_info = [
|
| 1347 |
+
(key, addr_pair) for key, addr_pair in addr_infos.items()
|
| 1348 |
+
if not ((local_addr and addr_pair[0] is None) or
|
| 1349 |
+
(remote_addr and addr_pair[1] is None))]
|
| 1350 |
+
|
| 1351 |
+
if not addr_pairs_info:
|
| 1352 |
+
raise ValueError('can not get address information')
|
| 1353 |
+
|
| 1354 |
+
exceptions = []
|
| 1355 |
+
|
| 1356 |
+
for ((family, proto),
|
| 1357 |
+
(local_address, remote_address)) in addr_pairs_info:
|
| 1358 |
+
sock = None
|
| 1359 |
+
r_addr = None
|
| 1360 |
+
try:
|
| 1361 |
+
sock = socket.socket(
|
| 1362 |
+
family=family, type=socket.SOCK_DGRAM, proto=proto)
|
| 1363 |
+
if reuse_port:
|
| 1364 |
+
_set_reuseport(sock)
|
| 1365 |
+
if allow_broadcast:
|
| 1366 |
+
sock.setsockopt(
|
| 1367 |
+
socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
| 1368 |
+
sock.setblocking(False)
|
| 1369 |
+
|
| 1370 |
+
if local_addr:
|
| 1371 |
+
sock.bind(local_address)
|
| 1372 |
+
if remote_addr:
|
| 1373 |
+
if not allow_broadcast:
|
| 1374 |
+
await self.sock_connect(sock, remote_address)
|
| 1375 |
+
r_addr = remote_address
|
| 1376 |
+
except OSError as exc:
|
| 1377 |
+
if sock is not None:
|
| 1378 |
+
sock.close()
|
| 1379 |
+
exceptions.append(exc)
|
| 1380 |
+
except:
|
| 1381 |
+
if sock is not None:
|
| 1382 |
+
sock.close()
|
| 1383 |
+
raise
|
| 1384 |
+
else:
|
| 1385 |
+
break
|
| 1386 |
+
else:
|
| 1387 |
+
raise exceptions[0]
|
| 1388 |
+
|
| 1389 |
+
protocol = protocol_factory()
|
| 1390 |
+
waiter = self.create_future()
|
| 1391 |
+
transport = self._make_datagram_transport(
|
| 1392 |
+
sock, protocol, r_addr, waiter)
|
| 1393 |
+
if self._debug:
|
| 1394 |
+
if local_addr:
|
| 1395 |
+
logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
|
| 1396 |
+
"created: (%r, %r)",
|
| 1397 |
+
local_addr, remote_addr, transport, protocol)
|
| 1398 |
+
else:
|
| 1399 |
+
logger.debug("Datagram endpoint remote_addr=%r created: "
|
| 1400 |
+
"(%r, %r)",
|
| 1401 |
+
remote_addr, transport, protocol)
|
| 1402 |
+
|
| 1403 |
+
try:
|
| 1404 |
+
await waiter
|
| 1405 |
+
except:
|
| 1406 |
+
transport.close()
|
| 1407 |
+
raise
|
| 1408 |
+
|
| 1409 |
+
return transport, protocol
|
| 1410 |
+
|
| 1411 |
+
async def _ensure_resolved(self, address, *,
|
| 1412 |
+
family=0, type=socket.SOCK_STREAM,
|
| 1413 |
+
proto=0, flags=0, loop):
|
| 1414 |
+
host, port = address[:2]
|
| 1415 |
+
info = _ipaddr_info(host, port, family, type, proto, *address[2:])
|
| 1416 |
+
if info is not None:
|
| 1417 |
+
# "host" is already a resolved IP.
|
| 1418 |
+
return [info]
|
| 1419 |
+
else:
|
| 1420 |
+
return await loop.getaddrinfo(host, port, family=family, type=type,
|
| 1421 |
+
proto=proto, flags=flags)
|
| 1422 |
+
|
| 1423 |
+
async def _create_server_getaddrinfo(self, host, port, family, flags):
|
| 1424 |
+
infos = await self._ensure_resolved((host, port), family=family,
|
| 1425 |
+
type=socket.SOCK_STREAM,
|
| 1426 |
+
flags=flags, loop=self)
|
| 1427 |
+
if not infos:
|
| 1428 |
+
raise OSError(f'getaddrinfo({host!r}) returned empty list')
|
| 1429 |
+
return infos
|
| 1430 |
+
|
| 1431 |
+
async def create_server(
|
| 1432 |
+
self, protocol_factory, host=None, port=None,
|
| 1433 |
+
*,
|
| 1434 |
+
family=socket.AF_UNSPEC,
|
| 1435 |
+
flags=socket.AI_PASSIVE,
|
| 1436 |
+
sock=None,
|
| 1437 |
+
backlog=100,
|
| 1438 |
+
ssl=None,
|
| 1439 |
+
reuse_address=None,
|
| 1440 |
+
reuse_port=None,
|
| 1441 |
+
ssl_handshake_timeout=None,
|
| 1442 |
+
ssl_shutdown_timeout=None,
|
| 1443 |
+
start_serving=True):
|
| 1444 |
+
"""Create a TCP server.
|
| 1445 |
+
|
| 1446 |
+
The host parameter can be a string, in that case the TCP server is
|
| 1447 |
+
bound to host and port.
|
| 1448 |
+
|
| 1449 |
+
The host parameter can also be a sequence of strings and in that case
|
| 1450 |
+
the TCP server is bound to all hosts of the sequence. If a host
|
| 1451 |
+
appears multiple times (possibly indirectly e.g. when hostnames
|
| 1452 |
+
resolve to the same IP address), the server is only bound once to that
|
| 1453 |
+
host.
|
| 1454 |
+
|
| 1455 |
+
Return a Server object which can be used to stop the service.
|
| 1456 |
+
|
| 1457 |
+
This method is a coroutine.
|
| 1458 |
+
"""
|
| 1459 |
+
if isinstance(ssl, bool):
|
| 1460 |
+
raise TypeError('ssl argument must be an SSLContext or None')
|
| 1461 |
+
|
| 1462 |
+
if ssl_handshake_timeout is not None and ssl is None:
|
| 1463 |
+
raise ValueError(
|
| 1464 |
+
'ssl_handshake_timeout is only meaningful with ssl')
|
| 1465 |
+
|
| 1466 |
+
if ssl_shutdown_timeout is not None and ssl is None:
|
| 1467 |
+
raise ValueError(
|
| 1468 |
+
'ssl_shutdown_timeout is only meaningful with ssl')
|
| 1469 |
+
|
| 1470 |
+
if sock is not None:
|
| 1471 |
+
_check_ssl_socket(sock)
|
| 1472 |
+
|
| 1473 |
+
if host is not None or port is not None:
|
| 1474 |
+
if sock is not None:
|
| 1475 |
+
raise ValueError(
|
| 1476 |
+
'host/port and sock can not be specified at the same time')
|
| 1477 |
+
|
| 1478 |
+
if reuse_address is None:
|
| 1479 |
+
reuse_address = os.name == "posix" and sys.platform != "cygwin"
|
| 1480 |
+
sockets = []
|
| 1481 |
+
if host == '':
|
| 1482 |
+
hosts = [None]
|
| 1483 |
+
elif (isinstance(host, str) or
|
| 1484 |
+
not isinstance(host, collections.abc.Iterable)):
|
| 1485 |
+
hosts = [host]
|
| 1486 |
+
else:
|
| 1487 |
+
hosts = host
|
| 1488 |
+
|
| 1489 |
+
fs = [self._create_server_getaddrinfo(host, port, family=family,
|
| 1490 |
+
flags=flags)
|
| 1491 |
+
for host in hosts]
|
| 1492 |
+
infos = await tasks.gather(*fs)
|
| 1493 |
+
infos = set(itertools.chain.from_iterable(infos))
|
| 1494 |
+
|
| 1495 |
+
completed = False
|
| 1496 |
+
try:
|
| 1497 |
+
for res in infos:
|
| 1498 |
+
af, socktype, proto, canonname, sa = res
|
| 1499 |
+
try:
|
| 1500 |
+
sock = socket.socket(af, socktype, proto)
|
| 1501 |
+
except socket.error:
|
| 1502 |
+
# Assume it's a bad family/type/protocol combination.
|
| 1503 |
+
if self._debug:
|
| 1504 |
+
logger.warning('create_server() failed to create '
|
| 1505 |
+
'socket.socket(%r, %r, %r)',
|
| 1506 |
+
af, socktype, proto, exc_info=True)
|
| 1507 |
+
continue
|
| 1508 |
+
sockets.append(sock)
|
| 1509 |
+
if reuse_address:
|
| 1510 |
+
sock.setsockopt(
|
| 1511 |
+
socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
|
| 1512 |
+
if reuse_port:
|
| 1513 |
+
_set_reuseport(sock)
|
| 1514 |
+
# Disable IPv4/IPv6 dual stack support (enabled by
|
| 1515 |
+
# default on Linux) which makes a single socket
|
| 1516 |
+
# listen on both address families.
|
| 1517 |
+
if (_HAS_IPv6 and
|
| 1518 |
+
af == socket.AF_INET6 and
|
| 1519 |
+
hasattr(socket, 'IPPROTO_IPV6')):
|
| 1520 |
+
sock.setsockopt(socket.IPPROTO_IPV6,
|
| 1521 |
+
socket.IPV6_V6ONLY,
|
| 1522 |
+
True)
|
| 1523 |
+
try:
|
| 1524 |
+
sock.bind(sa)
|
| 1525 |
+
except OSError as err:
|
| 1526 |
+
msg = ('error while attempting '
|
| 1527 |
+
'to bind on address %r: %s'
|
| 1528 |
+
% (sa, err.strerror.lower()))
|
| 1529 |
+
if err.errno == errno.EADDRNOTAVAIL:
|
| 1530 |
+
# Assume the family is not enabled (bpo-30945)
|
| 1531 |
+
sockets.pop()
|
| 1532 |
+
sock.close()
|
| 1533 |
+
if self._debug:
|
| 1534 |
+
logger.warning(msg)
|
| 1535 |
+
continue
|
| 1536 |
+
raise OSError(err.errno, msg) from None
|
| 1537 |
+
|
| 1538 |
+
if not sockets:
|
| 1539 |
+
raise OSError('could not bind on any address out of %r'
|
| 1540 |
+
% ([info[4] for info in infos],))
|
| 1541 |
+
|
| 1542 |
+
completed = True
|
| 1543 |
+
finally:
|
| 1544 |
+
if not completed:
|
| 1545 |
+
for sock in sockets:
|
| 1546 |
+
sock.close()
|
| 1547 |
+
else:
|
| 1548 |
+
if sock is None:
|
| 1549 |
+
raise ValueError('Neither host/port nor sock were specified')
|
| 1550 |
+
if sock.type != socket.SOCK_STREAM:
|
| 1551 |
+
raise ValueError(f'A Stream Socket was expected, got {sock!r}')
|
| 1552 |
+
sockets = [sock]
|
| 1553 |
+
|
| 1554 |
+
for sock in sockets:
|
| 1555 |
+
sock.setblocking(False)
|
| 1556 |
+
|
| 1557 |
+
server = Server(self, sockets, protocol_factory,
|
| 1558 |
+
ssl, backlog, ssl_handshake_timeout,
|
| 1559 |
+
ssl_shutdown_timeout)
|
| 1560 |
+
if start_serving:
|
| 1561 |
+
server._start_serving()
|
| 1562 |
+
# Skip one loop iteration so that all 'loop.add_reader'
|
| 1563 |
+
# go through.
|
| 1564 |
+
await tasks.sleep(0)
|
| 1565 |
+
|
| 1566 |
+
if self._debug:
|
| 1567 |
+
logger.info("%r is serving", server)
|
| 1568 |
+
return server
|
| 1569 |
+
|
| 1570 |
+
async def connect_accepted_socket(
|
| 1571 |
+
self, protocol_factory, sock,
|
| 1572 |
+
*, ssl=None,
|
| 1573 |
+
ssl_handshake_timeout=None,
|
| 1574 |
+
ssl_shutdown_timeout=None):
|
| 1575 |
+
if sock.type != socket.SOCK_STREAM:
|
| 1576 |
+
raise ValueError(f'A Stream Socket was expected, got {sock!r}')
|
| 1577 |
+
|
| 1578 |
+
if ssl_handshake_timeout is not None and not ssl:
|
| 1579 |
+
raise ValueError(
|
| 1580 |
+
'ssl_handshake_timeout is only meaningful with ssl')
|
| 1581 |
+
|
| 1582 |
+
if ssl_shutdown_timeout is not None and not ssl:
|
| 1583 |
+
raise ValueError(
|
| 1584 |
+
'ssl_shutdown_timeout is only meaningful with ssl')
|
| 1585 |
+
|
| 1586 |
+
if sock is not None:
|
| 1587 |
+
_check_ssl_socket(sock)
|
| 1588 |
+
|
| 1589 |
+
transport, protocol = await self._create_connection_transport(
|
| 1590 |
+
sock, protocol_factory, ssl, '', server_side=True,
|
| 1591 |
+
ssl_handshake_timeout=ssl_handshake_timeout,
|
| 1592 |
+
ssl_shutdown_timeout=ssl_shutdown_timeout)
|
| 1593 |
+
if self._debug:
|
| 1594 |
+
# Get the socket from the transport because SSL transport closes
|
| 1595 |
+
# the old socket and creates a new SSL socket
|
| 1596 |
+
sock = transport.get_extra_info('socket')
|
| 1597 |
+
logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
|
| 1598 |
+
return transport, protocol
|
| 1599 |
+
|
| 1600 |
+
async def connect_read_pipe(self, protocol_factory, pipe):
|
| 1601 |
+
protocol = protocol_factory()
|
| 1602 |
+
waiter = self.create_future()
|
| 1603 |
+
transport = self._make_read_pipe_transport(pipe, protocol, waiter)
|
| 1604 |
+
|
| 1605 |
+
try:
|
| 1606 |
+
await waiter
|
| 1607 |
+
except:
|
| 1608 |
+
transport.close()
|
| 1609 |
+
raise
|
| 1610 |
+
|
| 1611 |
+
if self._debug:
|
| 1612 |
+
logger.debug('Read pipe %r connected: (%r, %r)',
|
| 1613 |
+
pipe.fileno(), transport, protocol)
|
| 1614 |
+
return transport, protocol
|
| 1615 |
+
|
| 1616 |
+
async def connect_write_pipe(self, protocol_factory, pipe):
|
| 1617 |
+
protocol = protocol_factory()
|
| 1618 |
+
waiter = self.create_future()
|
| 1619 |
+
transport = self._make_write_pipe_transport(pipe, protocol, waiter)
|
| 1620 |
+
|
| 1621 |
+
try:
|
| 1622 |
+
await waiter
|
| 1623 |
+
except:
|
| 1624 |
+
transport.close()
|
| 1625 |
+
raise
|
| 1626 |
+
|
| 1627 |
+
if self._debug:
|
| 1628 |
+
logger.debug('Write pipe %r connected: (%r, %r)',
|
| 1629 |
+
pipe.fileno(), transport, protocol)
|
| 1630 |
+
return transport, protocol
|
| 1631 |
+
|
| 1632 |
+
def _log_subprocess(self, msg, stdin, stdout, stderr):
|
| 1633 |
+
info = [msg]
|
| 1634 |
+
if stdin is not None:
|
| 1635 |
+
info.append(f'stdin={_format_pipe(stdin)}')
|
| 1636 |
+
if stdout is not None and stderr == subprocess.STDOUT:
|
| 1637 |
+
info.append(f'stdout=stderr={_format_pipe(stdout)}')
|
| 1638 |
+
else:
|
| 1639 |
+
if stdout is not None:
|
| 1640 |
+
info.append(f'stdout={_format_pipe(stdout)}')
|
| 1641 |
+
if stderr is not None:
|
| 1642 |
+
info.append(f'stderr={_format_pipe(stderr)}')
|
| 1643 |
+
logger.debug(' '.join(info))
|
| 1644 |
+
|
| 1645 |
+
async def subprocess_shell(self, protocol_factory, cmd, *,
|
| 1646 |
+
stdin=subprocess.PIPE,
|
| 1647 |
+
stdout=subprocess.PIPE,
|
| 1648 |
+
stderr=subprocess.PIPE,
|
| 1649 |
+
universal_newlines=False,
|
| 1650 |
+
shell=True, bufsize=0,
|
| 1651 |
+
encoding=None, errors=None, text=None,
|
| 1652 |
+
**kwargs):
|
| 1653 |
+
if not isinstance(cmd, (bytes, str)):
|
| 1654 |
+
raise ValueError("cmd must be a string")
|
| 1655 |
+
if universal_newlines:
|
| 1656 |
+
raise ValueError("universal_newlines must be False")
|
| 1657 |
+
if not shell:
|
| 1658 |
+
raise ValueError("shell must be True")
|
| 1659 |
+
if bufsize != 0:
|
| 1660 |
+
raise ValueError("bufsize must be 0")
|
| 1661 |
+
if text:
|
| 1662 |
+
raise ValueError("text must be False")
|
| 1663 |
+
if encoding is not None:
|
| 1664 |
+
raise ValueError("encoding must be None")
|
| 1665 |
+
if errors is not None:
|
| 1666 |
+
raise ValueError("errors must be None")
|
| 1667 |
+
|
| 1668 |
+
protocol = protocol_factory()
|
| 1669 |
+
debug_log = None
|
| 1670 |
+
if self._debug:
|
| 1671 |
+
# don't log parameters: they may contain sensitive information
|
| 1672 |
+
# (password) and may be too long
|
| 1673 |
+
debug_log = 'run shell command %r' % cmd
|
| 1674 |
+
self._log_subprocess(debug_log, stdin, stdout, stderr)
|
| 1675 |
+
transport = await self._make_subprocess_transport(
|
| 1676 |
+
protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
|
| 1677 |
+
if self._debug and debug_log is not None:
|
| 1678 |
+
logger.info('%s: %r', debug_log, transport)
|
| 1679 |
+
return transport, protocol
|
| 1680 |
+
|
| 1681 |
+
async def subprocess_exec(self, protocol_factory, program, *args,
|
| 1682 |
+
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
| 1683 |
+
stderr=subprocess.PIPE, universal_newlines=False,
|
| 1684 |
+
shell=False, bufsize=0,
|
| 1685 |
+
encoding=None, errors=None, text=None,
|
| 1686 |
+
**kwargs):
|
| 1687 |
+
if universal_newlines:
|
| 1688 |
+
raise ValueError("universal_newlines must be False")
|
| 1689 |
+
if shell:
|
| 1690 |
+
raise ValueError("shell must be False")
|
| 1691 |
+
if bufsize != 0:
|
| 1692 |
+
raise ValueError("bufsize must be 0")
|
| 1693 |
+
if text:
|
| 1694 |
+
raise ValueError("text must be False")
|
| 1695 |
+
if encoding is not None:
|
| 1696 |
+
raise ValueError("encoding must be None")
|
| 1697 |
+
if errors is not None:
|
| 1698 |
+
raise ValueError("errors must be None")
|
| 1699 |
+
|
| 1700 |
+
popen_args = (program,) + args
|
| 1701 |
+
protocol = protocol_factory()
|
| 1702 |
+
debug_log = None
|
| 1703 |
+
if self._debug:
|
| 1704 |
+
# don't log parameters: they may contain sensitive information
|
| 1705 |
+
# (password) and may be too long
|
| 1706 |
+
debug_log = f'execute program {program!r}'
|
| 1707 |
+
self._log_subprocess(debug_log, stdin, stdout, stderr)
|
| 1708 |
+
transport = await self._make_subprocess_transport(
|
| 1709 |
+
protocol, popen_args, False, stdin, stdout, stderr,
|
| 1710 |
+
bufsize, **kwargs)
|
| 1711 |
+
if self._debug and debug_log is not None:
|
| 1712 |
+
logger.info('%s: %r', debug_log, transport)
|
| 1713 |
+
return transport, protocol
|
| 1714 |
+
|
| 1715 |
+
def get_exception_handler(self):
|
| 1716 |
+
"""Return an exception handler, or None if the default one is in use.
|
| 1717 |
+
"""
|
| 1718 |
+
return self._exception_handler
|
| 1719 |
+
|
| 1720 |
+
def set_exception_handler(self, handler):
|
| 1721 |
+
"""Set handler as the new event loop exception handler.
|
| 1722 |
+
|
| 1723 |
+
If handler is None, the default exception handler will
|
| 1724 |
+
be set.
|
| 1725 |
+
|
| 1726 |
+
If handler is a callable object, it should have a
|
| 1727 |
+
signature matching '(loop, context)', where 'loop'
|
| 1728 |
+
will be a reference to the active event loop, 'context'
|
| 1729 |
+
will be a dict object (see `call_exception_handler()`
|
| 1730 |
+
documentation for details about context).
|
| 1731 |
+
"""
|
| 1732 |
+
if handler is not None and not callable(handler):
|
| 1733 |
+
raise TypeError(f'A callable object or None is expected, '
|
| 1734 |
+
f'got {handler!r}')
|
| 1735 |
+
self._exception_handler = handler
|
| 1736 |
+
|
| 1737 |
+
def default_exception_handler(self, context):
|
| 1738 |
+
"""Default exception handler.
|
| 1739 |
+
|
| 1740 |
+
This is called when an exception occurs and no exception
|
| 1741 |
+
handler is set, and can be called by a custom exception
|
| 1742 |
+
handler that wants to defer to the default behavior.
|
| 1743 |
+
|
| 1744 |
+
This default handler logs the error message and other
|
| 1745 |
+
context-dependent information. In debug mode, a truncated
|
| 1746 |
+
stack trace is also appended showing where the given object
|
| 1747 |
+
(e.g. a handle or future or task) was created, if any.
|
| 1748 |
+
|
| 1749 |
+
The context parameter has the same meaning as in
|
| 1750 |
+
`call_exception_handler()`.
|
| 1751 |
+
"""
|
| 1752 |
+
message = context.get('message')
|
| 1753 |
+
if not message:
|
| 1754 |
+
message = 'Unhandled exception in event loop'
|
| 1755 |
+
|
| 1756 |
+
exception = context.get('exception')
|
| 1757 |
+
if exception is not None:
|
| 1758 |
+
exc_info = (type(exception), exception, exception.__traceback__)
|
| 1759 |
+
else:
|
| 1760 |
+
exc_info = False
|
| 1761 |
+
|
| 1762 |
+
if ('source_traceback' not in context and
|
| 1763 |
+
self._current_handle is not None and
|
| 1764 |
+
self._current_handle._source_traceback):
|
| 1765 |
+
context['handle_traceback'] = \
|
| 1766 |
+
self._current_handle._source_traceback
|
| 1767 |
+
|
| 1768 |
+
log_lines = [message]
|
| 1769 |
+
for key in sorted(context):
|
| 1770 |
+
if key in {'message', 'exception'}:
|
| 1771 |
+
continue
|
| 1772 |
+
value = context[key]
|
| 1773 |
+
if key == 'source_traceback':
|
| 1774 |
+
tb = ''.join(traceback.format_list(value))
|
| 1775 |
+
value = 'Object created at (most recent call last):\n'
|
| 1776 |
+
value += tb.rstrip()
|
| 1777 |
+
elif key == 'handle_traceback':
|
| 1778 |
+
tb = ''.join(traceback.format_list(value))
|
| 1779 |
+
value = 'Handle created at (most recent call last):\n'
|
| 1780 |
+
value += tb.rstrip()
|
| 1781 |
+
else:
|
| 1782 |
+
value = repr(value)
|
| 1783 |
+
log_lines.append(f'{key}: {value}')
|
| 1784 |
+
|
| 1785 |
+
logger.error('\n'.join(log_lines), exc_info=exc_info)
|
| 1786 |
+
|
| 1787 |
+
def call_exception_handler(self, context):
|
| 1788 |
+
"""Call the current event loop's exception handler.
|
| 1789 |
+
|
| 1790 |
+
The context argument is a dict containing the following keys:
|
| 1791 |
+
|
| 1792 |
+
- 'message': Error message;
|
| 1793 |
+
- 'exception' (optional): Exception object;
|
| 1794 |
+
- 'future' (optional): Future instance;
|
| 1795 |
+
- 'task' (optional): Task instance;
|
| 1796 |
+
- 'handle' (optional): Handle instance;
|
| 1797 |
+
- 'protocol' (optional): Protocol instance;
|
| 1798 |
+
- 'transport' (optional): Transport instance;
|
| 1799 |
+
- 'socket' (optional): Socket instance;
|
| 1800 |
+
- 'asyncgen' (optional): Asynchronous generator that caused
|
| 1801 |
+
the exception.
|
| 1802 |
+
|
| 1803 |
+
New keys maybe introduced in the future.
|
| 1804 |
+
|
| 1805 |
+
Note: do not overload this method in an event loop subclass.
|
| 1806 |
+
For custom exception handling, use the
|
| 1807 |
+
`set_exception_handler()` method.
|
| 1808 |
+
"""
|
| 1809 |
+
if self._exception_handler is None:
|
| 1810 |
+
try:
|
| 1811 |
+
self.default_exception_handler(context)
|
| 1812 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1813 |
+
raise
|
| 1814 |
+
except BaseException:
|
| 1815 |
+
# Second protection layer for unexpected errors
|
| 1816 |
+
# in the default implementation, as well as for subclassed
|
| 1817 |
+
# event loops with overloaded "default_exception_handler".
|
| 1818 |
+
logger.error('Exception in default exception handler',
|
| 1819 |
+
exc_info=True)
|
| 1820 |
+
else:
|
| 1821 |
+
try:
|
| 1822 |
+
self._exception_handler(self, context)
|
| 1823 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1824 |
+
raise
|
| 1825 |
+
except BaseException as exc:
|
| 1826 |
+
# Exception in the user set custom exception handler.
|
| 1827 |
+
try:
|
| 1828 |
+
# Let's try default handler.
|
| 1829 |
+
self.default_exception_handler({
|
| 1830 |
+
'message': 'Unhandled error in exception handler',
|
| 1831 |
+
'exception': exc,
|
| 1832 |
+
'context': context,
|
| 1833 |
+
})
|
| 1834 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1835 |
+
raise
|
| 1836 |
+
except BaseException:
|
| 1837 |
+
# Guard 'default_exception_handler' in case it is
|
| 1838 |
+
# overloaded.
|
| 1839 |
+
logger.error('Exception in default exception handler '
|
| 1840 |
+
'while handling an unexpected error '
|
| 1841 |
+
'in custom exception handler',
|
| 1842 |
+
exc_info=True)
|
| 1843 |
+
|
| 1844 |
+
def _add_callback(self, handle):
|
| 1845 |
+
"""Add a Handle to _ready."""
|
| 1846 |
+
if not handle._cancelled:
|
| 1847 |
+
self._ready.append(handle)
|
| 1848 |
+
|
| 1849 |
+
def _add_callback_signalsafe(self, handle):
|
| 1850 |
+
"""Like _add_callback() but called from a signal handler."""
|
| 1851 |
+
self._add_callback(handle)
|
| 1852 |
+
self._write_to_self()
|
| 1853 |
+
|
| 1854 |
+
def _timer_handle_cancelled(self, handle):
|
| 1855 |
+
"""Notification that a TimerHandle has been cancelled."""
|
| 1856 |
+
if handle._scheduled:
|
| 1857 |
+
self._timer_cancelled_count += 1
|
| 1858 |
+
|
| 1859 |
+
def _run_once(self):
|
| 1860 |
+
"""Run one full iteration of the event loop.
|
| 1861 |
+
|
| 1862 |
+
This calls all currently ready callbacks, polls for I/O,
|
| 1863 |
+
schedules the resulting callbacks, and finally schedules
|
| 1864 |
+
'call_later' callbacks.
|
| 1865 |
+
"""
|
| 1866 |
+
|
| 1867 |
+
sched_count = len(self._scheduled)
|
| 1868 |
+
if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
|
| 1869 |
+
self._timer_cancelled_count / sched_count >
|
| 1870 |
+
_MIN_CANCELLED_TIMER_HANDLES_FRACTION):
|
| 1871 |
+
# Remove delayed calls that were cancelled if their number
|
| 1872 |
+
# is too high
|
| 1873 |
+
new_scheduled = []
|
| 1874 |
+
for handle in self._scheduled:
|
| 1875 |
+
if handle._cancelled:
|
| 1876 |
+
handle._scheduled = False
|
| 1877 |
+
else:
|
| 1878 |
+
new_scheduled.append(handle)
|
| 1879 |
+
|
| 1880 |
+
heapq.heapify(new_scheduled)
|
| 1881 |
+
self._scheduled = new_scheduled
|
| 1882 |
+
self._timer_cancelled_count = 0
|
| 1883 |
+
else:
|
| 1884 |
+
# Remove delayed calls that were cancelled from head of queue.
|
| 1885 |
+
while self._scheduled and self._scheduled[0]._cancelled:
|
| 1886 |
+
self._timer_cancelled_count -= 1
|
| 1887 |
+
handle = heapq.heappop(self._scheduled)
|
| 1888 |
+
handle._scheduled = False
|
| 1889 |
+
|
| 1890 |
+
timeout = None
|
| 1891 |
+
if self._ready or self._stopping:
|
| 1892 |
+
timeout = 0
|
| 1893 |
+
elif self._scheduled:
|
| 1894 |
+
# Compute the desired timeout.
|
| 1895 |
+
when = self._scheduled[0]._when
|
| 1896 |
+
timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
|
| 1897 |
+
|
| 1898 |
+
event_list = self._selector.select(timeout)
|
| 1899 |
+
self._process_events(event_list)
|
| 1900 |
+
# Needed to break cycles when an exception occurs.
|
| 1901 |
+
event_list = None
|
| 1902 |
+
|
| 1903 |
+
# Handle 'later' callbacks that are ready.
|
| 1904 |
+
end_time = self.time() + self._clock_resolution
|
| 1905 |
+
while self._scheduled:
|
| 1906 |
+
handle = self._scheduled[0]
|
| 1907 |
+
if handle._when >= end_time:
|
| 1908 |
+
break
|
| 1909 |
+
handle = heapq.heappop(self._scheduled)
|
| 1910 |
+
handle._scheduled = False
|
| 1911 |
+
self._ready.append(handle)
|
| 1912 |
+
|
| 1913 |
+
# This is the only place where callbacks are actually *called*.
|
| 1914 |
+
# All other places just add them to ready.
|
| 1915 |
+
# Note: We run all currently scheduled callbacks, but not any
|
| 1916 |
+
# callbacks scheduled by callbacks run this time around --
|
| 1917 |
+
# they will be run the next time (after another I/O poll).
|
| 1918 |
+
# Use an idiom that is thread-safe without using locks.
|
| 1919 |
+
ntodo = len(self._ready)
|
| 1920 |
+
for i in range(ntodo):
|
| 1921 |
+
handle = self._ready.popleft()
|
| 1922 |
+
if handle._cancelled:
|
| 1923 |
+
continue
|
| 1924 |
+
if self._debug:
|
| 1925 |
+
try:
|
| 1926 |
+
self._current_handle = handle
|
| 1927 |
+
t0 = self.time()
|
| 1928 |
+
handle._run()
|
| 1929 |
+
dt = self.time() - t0
|
| 1930 |
+
if dt >= self.slow_callback_duration:
|
| 1931 |
+
logger.warning('Executing %s took %.3f seconds',
|
| 1932 |
+
_format_handle(handle), dt)
|
| 1933 |
+
finally:
|
| 1934 |
+
self._current_handle = None
|
| 1935 |
+
else:
|
| 1936 |
+
handle._run()
|
| 1937 |
+
handle = None # Needed to break cycles when an exception occurs.
|
| 1938 |
+
|
| 1939 |
+
def _set_coroutine_origin_tracking(self, enabled):
|
| 1940 |
+
if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
|
| 1941 |
+
return
|
| 1942 |
+
|
| 1943 |
+
if enabled:
|
| 1944 |
+
self._coroutine_origin_tracking_saved_depth = (
|
| 1945 |
+
sys.get_coroutine_origin_tracking_depth())
|
| 1946 |
+
sys.set_coroutine_origin_tracking_depth(
|
| 1947 |
+
constants.DEBUG_STACK_DEPTH)
|
| 1948 |
+
else:
|
| 1949 |
+
sys.set_coroutine_origin_tracking_depth(
|
| 1950 |
+
self._coroutine_origin_tracking_saved_depth)
|
| 1951 |
+
|
| 1952 |
+
self._coroutine_origin_tracking_enabled = enabled
|
| 1953 |
+
|
| 1954 |
+
def get_debug(self):
|
| 1955 |
+
return self._debug
|
| 1956 |
+
|
| 1957 |
+
def set_debug(self, enabled):
|
| 1958 |
+
self._debug = enabled
|
| 1959 |
+
|
| 1960 |
+
if self.is_running():
|
| 1961 |
+
self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)
|
micromamba_root/envs/pytorch_env/Lib/asyncio/base_futures.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = ()
|
| 2 |
+
|
| 3 |
+
import reprlib
|
| 4 |
+
from _thread import get_ident
|
| 5 |
+
|
| 6 |
+
from . import format_helpers
|
| 7 |
+
|
| 8 |
+
# States for Future.
|
| 9 |
+
_PENDING = 'PENDING'
|
| 10 |
+
_CANCELLED = 'CANCELLED'
|
| 11 |
+
_FINISHED = 'FINISHED'
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def isfuture(obj):
|
| 15 |
+
"""Check for a Future.
|
| 16 |
+
|
| 17 |
+
This returns True when obj is a Future instance or is advertising
|
| 18 |
+
itself as duck-type compatible by setting _asyncio_future_blocking.
|
| 19 |
+
See comment in Future for more details.
|
| 20 |
+
"""
|
| 21 |
+
return (hasattr(obj.__class__, '_asyncio_future_blocking') and
|
| 22 |
+
obj._asyncio_future_blocking is not None)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _format_callbacks(cb):
|
| 26 |
+
"""helper function for Future.__repr__"""
|
| 27 |
+
size = len(cb)
|
| 28 |
+
if not size:
|
| 29 |
+
cb = ''
|
| 30 |
+
|
| 31 |
+
def format_cb(callback):
|
| 32 |
+
return format_helpers._format_callback_source(callback, ())
|
| 33 |
+
|
| 34 |
+
if size == 1:
|
| 35 |
+
cb = format_cb(cb[0][0])
|
| 36 |
+
elif size == 2:
|
| 37 |
+
cb = '{}, {}'.format(format_cb(cb[0][0]), format_cb(cb[1][0]))
|
| 38 |
+
elif size > 2:
|
| 39 |
+
cb = '{}, <{} more>, {}'.format(format_cb(cb[0][0]),
|
| 40 |
+
size - 2,
|
| 41 |
+
format_cb(cb[-1][0]))
|
| 42 |
+
return f'cb=[{cb}]'
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _future_repr_info(future):
|
| 46 |
+
# (Future) -> str
|
| 47 |
+
"""helper function for Future.__repr__"""
|
| 48 |
+
info = [future._state.lower()]
|
| 49 |
+
if future._state == _FINISHED:
|
| 50 |
+
if future._exception is not None:
|
| 51 |
+
info.append(f'exception={future._exception!r}')
|
| 52 |
+
else:
|
| 53 |
+
# use reprlib to limit the length of the output, especially
|
| 54 |
+
# for very long strings
|
| 55 |
+
result = reprlib.repr(future._result)
|
| 56 |
+
info.append(f'result={result}')
|
| 57 |
+
if future._callbacks:
|
| 58 |
+
info.append(_format_callbacks(future._callbacks))
|
| 59 |
+
if future._source_traceback:
|
| 60 |
+
frame = future._source_traceback[-1]
|
| 61 |
+
info.append(f'created at {frame[0]}:{frame[1]}')
|
| 62 |
+
return info
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@reprlib.recursive_repr()
|
| 66 |
+
def _future_repr(future):
|
| 67 |
+
info = ' '.join(_future_repr_info(future))
|
| 68 |
+
return f'<{future.__class__.__name__} {info}>'
|
micromamba_root/envs/pytorch_env/Lib/asyncio/base_subprocess.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
import subprocess
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
from . import protocols
|
| 6 |
+
from . import transports
|
| 7 |
+
from .log import logger
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class BaseSubprocessTransport(transports.SubprocessTransport):
|
| 11 |
+
|
| 12 |
+
def __init__(self, loop, protocol, args, shell,
|
| 13 |
+
stdin, stdout, stderr, bufsize,
|
| 14 |
+
waiter=None, extra=None, **kwargs):
|
| 15 |
+
super().__init__(extra)
|
| 16 |
+
self._closed = False
|
| 17 |
+
self._protocol = protocol
|
| 18 |
+
self._loop = loop
|
| 19 |
+
self._proc = None
|
| 20 |
+
self._pid = None
|
| 21 |
+
self._returncode = None
|
| 22 |
+
self._exit_waiters = []
|
| 23 |
+
self._pending_calls = collections.deque()
|
| 24 |
+
self._pipes = {}
|
| 25 |
+
self._finished = False
|
| 26 |
+
|
| 27 |
+
if stdin == subprocess.PIPE:
|
| 28 |
+
self._pipes[0] = None
|
| 29 |
+
if stdout == subprocess.PIPE:
|
| 30 |
+
self._pipes[1] = None
|
| 31 |
+
if stderr == subprocess.PIPE:
|
| 32 |
+
self._pipes[2] = None
|
| 33 |
+
|
| 34 |
+
# Create the child process: set the _proc attribute
|
| 35 |
+
try:
|
| 36 |
+
self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
|
| 37 |
+
stderr=stderr, bufsize=bufsize, **kwargs)
|
| 38 |
+
except:
|
| 39 |
+
self.close()
|
| 40 |
+
raise
|
| 41 |
+
|
| 42 |
+
self._pid = self._proc.pid
|
| 43 |
+
self._extra['subprocess'] = self._proc
|
| 44 |
+
|
| 45 |
+
if self._loop.get_debug():
|
| 46 |
+
if isinstance(args, (bytes, str)):
|
| 47 |
+
program = args
|
| 48 |
+
else:
|
| 49 |
+
program = args[0]
|
| 50 |
+
logger.debug('process %r created: pid %s',
|
| 51 |
+
program, self._pid)
|
| 52 |
+
|
| 53 |
+
self._loop.create_task(self._connect_pipes(waiter))
|
| 54 |
+
|
| 55 |
+
def __repr__(self):
|
| 56 |
+
info = [self.__class__.__name__]
|
| 57 |
+
if self._closed:
|
| 58 |
+
info.append('closed')
|
| 59 |
+
if self._pid is not None:
|
| 60 |
+
info.append(f'pid={self._pid}')
|
| 61 |
+
if self._returncode is not None:
|
| 62 |
+
info.append(f'returncode={self._returncode}')
|
| 63 |
+
elif self._pid is not None:
|
| 64 |
+
info.append('running')
|
| 65 |
+
else:
|
| 66 |
+
info.append('not started')
|
| 67 |
+
|
| 68 |
+
stdin = self._pipes.get(0)
|
| 69 |
+
if stdin is not None:
|
| 70 |
+
info.append(f'stdin={stdin.pipe}')
|
| 71 |
+
|
| 72 |
+
stdout = self._pipes.get(1)
|
| 73 |
+
stderr = self._pipes.get(2)
|
| 74 |
+
if stdout is not None and stderr is stdout:
|
| 75 |
+
info.append(f'stdout=stderr={stdout.pipe}')
|
| 76 |
+
else:
|
| 77 |
+
if stdout is not None:
|
| 78 |
+
info.append(f'stdout={stdout.pipe}')
|
| 79 |
+
if stderr is not None:
|
| 80 |
+
info.append(f'stderr={stderr.pipe}')
|
| 81 |
+
|
| 82 |
+
return '<{}>'.format(' '.join(info))
|
| 83 |
+
|
| 84 |
+
def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
|
| 85 |
+
raise NotImplementedError
|
| 86 |
+
|
| 87 |
+
def set_protocol(self, protocol):
|
| 88 |
+
self._protocol = protocol
|
| 89 |
+
|
| 90 |
+
def get_protocol(self):
|
| 91 |
+
return self._protocol
|
| 92 |
+
|
| 93 |
+
def is_closing(self):
|
| 94 |
+
return self._closed
|
| 95 |
+
|
| 96 |
+
def close(self):
|
| 97 |
+
if self._closed:
|
| 98 |
+
return
|
| 99 |
+
self._closed = True
|
| 100 |
+
|
| 101 |
+
for proto in self._pipes.values():
|
| 102 |
+
if proto is None:
|
| 103 |
+
continue
|
| 104 |
+
proto.pipe.close()
|
| 105 |
+
|
| 106 |
+
if (self._proc is not None and
|
| 107 |
+
# has the child process finished?
|
| 108 |
+
self._returncode is None and
|
| 109 |
+
# the child process has finished, but the
|
| 110 |
+
# transport hasn't been notified yet?
|
| 111 |
+
self._proc.poll() is None):
|
| 112 |
+
|
| 113 |
+
if self._loop.get_debug():
|
| 114 |
+
logger.warning('Close running child process: kill %r', self)
|
| 115 |
+
|
| 116 |
+
try:
|
| 117 |
+
self._proc.kill()
|
| 118 |
+
except ProcessLookupError:
|
| 119 |
+
pass
|
| 120 |
+
|
| 121 |
+
# Don't clear the _proc reference yet: _post_init() may still run
|
| 122 |
+
|
| 123 |
+
def __del__(self, _warn=warnings.warn):
|
| 124 |
+
if not self._closed:
|
| 125 |
+
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
|
| 126 |
+
self.close()
|
| 127 |
+
|
| 128 |
+
def get_pid(self):
|
| 129 |
+
return self._pid
|
| 130 |
+
|
| 131 |
+
def get_returncode(self):
|
| 132 |
+
return self._returncode
|
| 133 |
+
|
| 134 |
+
def get_pipe_transport(self, fd):
|
| 135 |
+
if fd in self._pipes:
|
| 136 |
+
return self._pipes[fd].pipe
|
| 137 |
+
else:
|
| 138 |
+
return None
|
| 139 |
+
|
| 140 |
+
def _check_proc(self):
|
| 141 |
+
if self._proc is None:
|
| 142 |
+
raise ProcessLookupError()
|
| 143 |
+
|
| 144 |
+
def send_signal(self, signal):
|
| 145 |
+
self._check_proc()
|
| 146 |
+
self._proc.send_signal(signal)
|
| 147 |
+
|
| 148 |
+
def terminate(self):
|
| 149 |
+
self._check_proc()
|
| 150 |
+
self._proc.terminate()
|
| 151 |
+
|
| 152 |
+
def kill(self):
|
| 153 |
+
self._check_proc()
|
| 154 |
+
self._proc.kill()
|
| 155 |
+
|
| 156 |
+
async def _connect_pipes(self, waiter):
|
| 157 |
+
try:
|
| 158 |
+
proc = self._proc
|
| 159 |
+
loop = self._loop
|
| 160 |
+
|
| 161 |
+
if proc.stdin is not None:
|
| 162 |
+
_, pipe = await loop.connect_write_pipe(
|
| 163 |
+
lambda: WriteSubprocessPipeProto(self, 0),
|
| 164 |
+
proc.stdin)
|
| 165 |
+
self._pipes[0] = pipe
|
| 166 |
+
|
| 167 |
+
if proc.stdout is not None:
|
| 168 |
+
_, pipe = await loop.connect_read_pipe(
|
| 169 |
+
lambda: ReadSubprocessPipeProto(self, 1),
|
| 170 |
+
proc.stdout)
|
| 171 |
+
self._pipes[1] = pipe
|
| 172 |
+
|
| 173 |
+
if proc.stderr is not None:
|
| 174 |
+
_, pipe = await loop.connect_read_pipe(
|
| 175 |
+
lambda: ReadSubprocessPipeProto(self, 2),
|
| 176 |
+
proc.stderr)
|
| 177 |
+
self._pipes[2] = pipe
|
| 178 |
+
|
| 179 |
+
assert self._pending_calls is not None
|
| 180 |
+
|
| 181 |
+
loop.call_soon(self._protocol.connection_made, self)
|
| 182 |
+
for callback, data in self._pending_calls:
|
| 183 |
+
loop.call_soon(callback, *data)
|
| 184 |
+
self._pending_calls = None
|
| 185 |
+
except (SystemExit, KeyboardInterrupt):
|
| 186 |
+
raise
|
| 187 |
+
except BaseException as exc:
|
| 188 |
+
if waiter is not None and not waiter.cancelled():
|
| 189 |
+
waiter.set_exception(exc)
|
| 190 |
+
else:
|
| 191 |
+
if waiter is not None and not waiter.cancelled():
|
| 192 |
+
waiter.set_result(None)
|
| 193 |
+
|
| 194 |
+
def _call(self, cb, *data):
|
| 195 |
+
if self._pending_calls is not None:
|
| 196 |
+
self._pending_calls.append((cb, data))
|
| 197 |
+
else:
|
| 198 |
+
self._loop.call_soon(cb, *data)
|
| 199 |
+
|
| 200 |
+
def _pipe_connection_lost(self, fd, exc):
|
| 201 |
+
self._call(self._protocol.pipe_connection_lost, fd, exc)
|
| 202 |
+
self._try_finish()
|
| 203 |
+
|
| 204 |
+
def _pipe_data_received(self, fd, data):
|
| 205 |
+
self._call(self._protocol.pipe_data_received, fd, data)
|
| 206 |
+
|
| 207 |
+
def _process_exited(self, returncode):
|
| 208 |
+
assert returncode is not None, returncode
|
| 209 |
+
assert self._returncode is None, self._returncode
|
| 210 |
+
if self._loop.get_debug():
|
| 211 |
+
logger.info('%r exited with return code %r', self, returncode)
|
| 212 |
+
self._returncode = returncode
|
| 213 |
+
if self._proc.returncode is None:
|
| 214 |
+
# asyncio uses a child watcher: copy the status into the Popen
|
| 215 |
+
# object. On Python 3.6, it is required to avoid a ResourceWarning.
|
| 216 |
+
self._proc.returncode = returncode
|
| 217 |
+
self._call(self._protocol.process_exited)
|
| 218 |
+
|
| 219 |
+
self._try_finish()
|
| 220 |
+
|
| 221 |
+
async def _wait(self):
|
| 222 |
+
"""Wait until the process exit and return the process return code.
|
| 223 |
+
|
| 224 |
+
This method is a coroutine."""
|
| 225 |
+
if self._returncode is not None:
|
| 226 |
+
return self._returncode
|
| 227 |
+
|
| 228 |
+
waiter = self._loop.create_future()
|
| 229 |
+
self._exit_waiters.append(waiter)
|
| 230 |
+
return await waiter
|
| 231 |
+
|
| 232 |
+
def _try_finish(self):
|
| 233 |
+
assert not self._finished
|
| 234 |
+
if self._returncode is None:
|
| 235 |
+
return
|
| 236 |
+
if all(p is not None and p.disconnected
|
| 237 |
+
for p in self._pipes.values()):
|
| 238 |
+
self._finished = True
|
| 239 |
+
self._call(self._call_connection_lost, None)
|
| 240 |
+
|
| 241 |
+
def _call_connection_lost(self, exc):
|
| 242 |
+
try:
|
| 243 |
+
self._protocol.connection_lost(exc)
|
| 244 |
+
finally:
|
| 245 |
+
# wake up futures waiting for wait()
|
| 246 |
+
for waiter in self._exit_waiters:
|
| 247 |
+
if not waiter.cancelled():
|
| 248 |
+
waiter.set_result(self._returncode)
|
| 249 |
+
self._exit_waiters = None
|
| 250 |
+
self._loop = None
|
| 251 |
+
self._proc = None
|
| 252 |
+
self._protocol = None
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class WriteSubprocessPipeProto(protocols.BaseProtocol):
|
| 256 |
+
|
| 257 |
+
def __init__(self, proc, fd):
|
| 258 |
+
self.proc = proc
|
| 259 |
+
self.fd = fd
|
| 260 |
+
self.pipe = None
|
| 261 |
+
self.disconnected = False
|
| 262 |
+
|
| 263 |
+
def connection_made(self, transport):
|
| 264 |
+
self.pipe = transport
|
| 265 |
+
|
| 266 |
+
def __repr__(self):
|
| 267 |
+
return f'<{self.__class__.__name__} fd={self.fd} pipe={self.pipe!r}>'
|
| 268 |
+
|
| 269 |
+
def connection_lost(self, exc):
|
| 270 |
+
self.disconnected = True
|
| 271 |
+
self.proc._pipe_connection_lost(self.fd, exc)
|
| 272 |
+
self.proc = None
|
| 273 |
+
|
| 274 |
+
def pause_writing(self):
|
| 275 |
+
self.proc._protocol.pause_writing()
|
| 276 |
+
|
| 277 |
+
def resume_writing(self):
|
| 278 |
+
self.proc._protocol.resume_writing()
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
|
| 282 |
+
protocols.Protocol):
|
| 283 |
+
|
| 284 |
+
def data_received(self, data):
|
| 285 |
+
self.proc._pipe_data_received(self.fd, data)
|
micromamba_root/envs/pytorch_env/Lib/asyncio/base_tasks.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import linecache
|
| 2 |
+
import reprlib
|
| 3 |
+
import traceback
|
| 4 |
+
|
| 5 |
+
from . import base_futures
|
| 6 |
+
from . import coroutines
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _task_repr_info(task):
|
| 10 |
+
info = base_futures._future_repr_info(task)
|
| 11 |
+
|
| 12 |
+
if task.cancelling() and not task.done():
|
| 13 |
+
# replace status
|
| 14 |
+
info[0] = 'cancelling'
|
| 15 |
+
|
| 16 |
+
info.insert(1, 'name=%r' % task.get_name())
|
| 17 |
+
|
| 18 |
+
coro = coroutines._format_coroutine(task._coro)
|
| 19 |
+
info.insert(2, f'coro=<{coro}>')
|
| 20 |
+
|
| 21 |
+
if task._fut_waiter is not None:
|
| 22 |
+
info.insert(3, f'wait_for={task._fut_waiter!r}')
|
| 23 |
+
return info
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@reprlib.recursive_repr()
|
| 27 |
+
def _task_repr(task):
|
| 28 |
+
info = ' '.join(_task_repr_info(task))
|
| 29 |
+
return f'<{task.__class__.__name__} {info}>'
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _task_get_stack(task, limit):
|
| 33 |
+
frames = []
|
| 34 |
+
if hasattr(task._coro, 'cr_frame'):
|
| 35 |
+
# case 1: 'async def' coroutines
|
| 36 |
+
f = task._coro.cr_frame
|
| 37 |
+
elif hasattr(task._coro, 'gi_frame'):
|
| 38 |
+
# case 2: legacy coroutines
|
| 39 |
+
f = task._coro.gi_frame
|
| 40 |
+
elif hasattr(task._coro, 'ag_frame'):
|
| 41 |
+
# case 3: async generators
|
| 42 |
+
f = task._coro.ag_frame
|
| 43 |
+
else:
|
| 44 |
+
# case 4: unknown objects
|
| 45 |
+
f = None
|
| 46 |
+
if f is not None:
|
| 47 |
+
while f is not None:
|
| 48 |
+
if limit is not None:
|
| 49 |
+
if limit <= 0:
|
| 50 |
+
break
|
| 51 |
+
limit -= 1
|
| 52 |
+
frames.append(f)
|
| 53 |
+
f = f.f_back
|
| 54 |
+
frames.reverse()
|
| 55 |
+
elif task._exception is not None:
|
| 56 |
+
tb = task._exception.__traceback__
|
| 57 |
+
while tb is not None:
|
| 58 |
+
if limit is not None:
|
| 59 |
+
if limit <= 0:
|
| 60 |
+
break
|
| 61 |
+
limit -= 1
|
| 62 |
+
frames.append(tb.tb_frame)
|
| 63 |
+
tb = tb.tb_next
|
| 64 |
+
return frames
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _task_print_stack(task, limit, file):
|
| 68 |
+
extracted_list = []
|
| 69 |
+
checked = set()
|
| 70 |
+
for f in task.get_stack(limit=limit):
|
| 71 |
+
lineno = f.f_lineno
|
| 72 |
+
co = f.f_code
|
| 73 |
+
filename = co.co_filename
|
| 74 |
+
name = co.co_name
|
| 75 |
+
if filename not in checked:
|
| 76 |
+
checked.add(filename)
|
| 77 |
+
linecache.checkcache(filename)
|
| 78 |
+
line = linecache.getline(filename, lineno, f.f_globals)
|
| 79 |
+
extracted_list.append((filename, lineno, name, line))
|
| 80 |
+
|
| 81 |
+
exc = task._exception
|
| 82 |
+
if not extracted_list:
|
| 83 |
+
print(f'No stack for {task!r}', file=file)
|
| 84 |
+
elif exc is not None:
|
| 85 |
+
print(f'Traceback for {task!r} (most recent call last):', file=file)
|
| 86 |
+
else:
|
| 87 |
+
print(f'Stack for {task!r} (most recent call last):', file=file)
|
| 88 |
+
|
| 89 |
+
traceback.print_list(extracted_list, file=file)
|
| 90 |
+
if exc is not None:
|
| 91 |
+
for line in traceback.format_exception_only(exc.__class__, exc):
|
| 92 |
+
print(line, file=file, end='')
|
micromamba_root/envs/pytorch_env/Lib/asyncio/constants.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Contains code from https://github.com/MagicStack/uvloop/tree/v0.16.0
|
| 2 |
+
# SPDX-License-Identifier: PSF-2.0 AND (MIT OR Apache-2.0)
|
| 3 |
+
# SPDX-FileCopyrightText: Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
|
| 4 |
+
|
| 5 |
+
import enum
|
| 6 |
+
|
| 7 |
+
# After the connection is lost, log warnings after this many write()s.
|
| 8 |
+
LOG_THRESHOLD_FOR_CONNLOST_WRITES = 5
|
| 9 |
+
|
| 10 |
+
# Seconds to wait before retrying accept().
|
| 11 |
+
ACCEPT_RETRY_DELAY = 1
|
| 12 |
+
|
| 13 |
+
# Number of stack entries to capture in debug mode.
|
| 14 |
+
# The larger the number, the slower the operation in debug mode
|
| 15 |
+
# (see extract_stack() in format_helpers.py).
|
| 16 |
+
DEBUG_STACK_DEPTH = 10
|
| 17 |
+
|
| 18 |
+
# Number of seconds to wait for SSL handshake to complete
|
| 19 |
+
# The default timeout matches that of Nginx.
|
| 20 |
+
SSL_HANDSHAKE_TIMEOUT = 60.0
|
| 21 |
+
|
| 22 |
+
# Number of seconds to wait for SSL shutdown to complete
|
| 23 |
+
# The default timeout mimics lingering_time
|
| 24 |
+
SSL_SHUTDOWN_TIMEOUT = 30.0
|
| 25 |
+
|
| 26 |
+
# Used in sendfile fallback code. We use fallback for platforms
|
| 27 |
+
# that don't support sendfile, or for TLS connections.
|
| 28 |
+
SENDFILE_FALLBACK_READBUFFER_SIZE = 1024 * 256
|
| 29 |
+
|
| 30 |
+
FLOW_CONTROL_HIGH_WATER_SSL_READ = 256 # KiB
|
| 31 |
+
FLOW_CONTROL_HIGH_WATER_SSL_WRITE = 512 # KiB
|
| 32 |
+
|
| 33 |
+
# The enum should be here to break circular dependencies between
|
| 34 |
+
# base_events and sslproto
|
| 35 |
+
class _SendfileMode(enum.Enum):
|
| 36 |
+
UNSUPPORTED = enum.auto()
|
| 37 |
+
TRY_NATIVE = enum.auto()
|
| 38 |
+
FALLBACK = enum.auto()
|
micromamba_root/envs/pytorch_env/Lib/asyncio/coroutines.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = 'iscoroutinefunction', 'iscoroutine'
|
| 2 |
+
|
| 3 |
+
import collections.abc
|
| 4 |
+
import inspect
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import traceback
|
| 8 |
+
import types
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _is_debug_mode():
|
| 12 |
+
# See: https://docs.python.org/3/library/asyncio-dev.html#asyncio-debug-mode.
|
| 13 |
+
return sys.flags.dev_mode or (not sys.flags.ignore_environment and
|
| 14 |
+
bool(os.environ.get('PYTHONASYNCIODEBUG')))
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# A marker for iscoroutinefunction.
|
| 18 |
+
_is_coroutine = object()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def iscoroutinefunction(func):
|
| 22 |
+
"""Return True if func is a decorated coroutine function."""
|
| 23 |
+
return (inspect.iscoroutinefunction(func) or
|
| 24 |
+
getattr(func, '_is_coroutine', None) is _is_coroutine)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# Prioritize native coroutine check to speed-up
|
| 28 |
+
# asyncio.iscoroutine.
|
| 29 |
+
_COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType,
|
| 30 |
+
collections.abc.Coroutine)
|
| 31 |
+
_iscoroutine_typecache = set()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def iscoroutine(obj):
|
| 35 |
+
"""Return True if obj is a coroutine object."""
|
| 36 |
+
if type(obj) in _iscoroutine_typecache:
|
| 37 |
+
return True
|
| 38 |
+
|
| 39 |
+
if isinstance(obj, _COROUTINE_TYPES):
|
| 40 |
+
# Just in case we don't want to cache more than 100
|
| 41 |
+
# positive types. That shouldn't ever happen, unless
|
| 42 |
+
# someone stressing the system on purpose.
|
| 43 |
+
if len(_iscoroutine_typecache) < 100:
|
| 44 |
+
_iscoroutine_typecache.add(type(obj))
|
| 45 |
+
return True
|
| 46 |
+
else:
|
| 47 |
+
return False
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _format_coroutine(coro):
|
| 51 |
+
assert iscoroutine(coro)
|
| 52 |
+
|
| 53 |
+
def get_name(coro):
|
| 54 |
+
# Coroutines compiled with Cython sometimes don't have
|
| 55 |
+
# proper __qualname__ or __name__. While that is a bug
|
| 56 |
+
# in Cython, asyncio shouldn't crash with an AttributeError
|
| 57 |
+
# in its __repr__ functions.
|
| 58 |
+
if hasattr(coro, '__qualname__') and coro.__qualname__:
|
| 59 |
+
coro_name = coro.__qualname__
|
| 60 |
+
elif hasattr(coro, '__name__') and coro.__name__:
|
| 61 |
+
coro_name = coro.__name__
|
| 62 |
+
else:
|
| 63 |
+
# Stop masking Cython bugs, expose them in a friendly way.
|
| 64 |
+
coro_name = f'<{type(coro).__name__} without __name__>'
|
| 65 |
+
return f'{coro_name}()'
|
| 66 |
+
|
| 67 |
+
def is_running(coro):
|
| 68 |
+
try:
|
| 69 |
+
return coro.cr_running
|
| 70 |
+
except AttributeError:
|
| 71 |
+
try:
|
| 72 |
+
return coro.gi_running
|
| 73 |
+
except AttributeError:
|
| 74 |
+
return False
|
| 75 |
+
|
| 76 |
+
coro_code = None
|
| 77 |
+
if hasattr(coro, 'cr_code') and coro.cr_code:
|
| 78 |
+
coro_code = coro.cr_code
|
| 79 |
+
elif hasattr(coro, 'gi_code') and coro.gi_code:
|
| 80 |
+
coro_code = coro.gi_code
|
| 81 |
+
|
| 82 |
+
coro_name = get_name(coro)
|
| 83 |
+
|
| 84 |
+
if not coro_code:
|
| 85 |
+
# Built-in types might not have __qualname__ or __name__.
|
| 86 |
+
if is_running(coro):
|
| 87 |
+
return f'{coro_name} running'
|
| 88 |
+
else:
|
| 89 |
+
return coro_name
|
| 90 |
+
|
| 91 |
+
coro_frame = None
|
| 92 |
+
if hasattr(coro, 'gi_frame') and coro.gi_frame:
|
| 93 |
+
coro_frame = coro.gi_frame
|
| 94 |
+
elif hasattr(coro, 'cr_frame') and coro.cr_frame:
|
| 95 |
+
coro_frame = coro.cr_frame
|
| 96 |
+
|
| 97 |
+
# If Cython's coroutine has a fake code object without proper
|
| 98 |
+
# co_filename -- expose that.
|
| 99 |
+
filename = coro_code.co_filename or '<empty co_filename>'
|
| 100 |
+
|
| 101 |
+
lineno = 0
|
| 102 |
+
|
| 103 |
+
if coro_frame is not None:
|
| 104 |
+
lineno = coro_frame.f_lineno
|
| 105 |
+
coro_repr = f'{coro_name} running at {filename}:{lineno}'
|
| 106 |
+
|
| 107 |
+
else:
|
| 108 |
+
lineno = coro_code.co_firstlineno
|
| 109 |
+
coro_repr = f'{coro_name} done, defined at {filename}:{lineno}'
|
| 110 |
+
|
| 111 |
+
return coro_repr
|
micromamba_root/envs/pytorch_env/Lib/asyncio/events.py
ADDED
|
@@ -0,0 +1,846 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event loop and event loop policy."""
|
| 2 |
+
|
| 3 |
+
# Contains code from https://github.com/MagicStack/uvloop/tree/v0.16.0
|
| 4 |
+
# SPDX-License-Identifier: PSF-2.0 AND (MIT OR Apache-2.0)
|
| 5 |
+
# SPDX-FileCopyrightText: Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
|
| 6 |
+
|
| 7 |
+
__all__ = (
|
| 8 |
+
'AbstractEventLoopPolicy',
|
| 9 |
+
'AbstractEventLoop', 'AbstractServer',
|
| 10 |
+
'Handle', 'TimerHandle',
|
| 11 |
+
'get_event_loop_policy', 'set_event_loop_policy',
|
| 12 |
+
'get_event_loop', 'set_event_loop', 'new_event_loop',
|
| 13 |
+
'get_child_watcher', 'set_child_watcher',
|
| 14 |
+
'_set_running_loop', 'get_running_loop',
|
| 15 |
+
'_get_running_loop',
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
import contextvars
|
| 19 |
+
import os
|
| 20 |
+
import socket
|
| 21 |
+
import subprocess
|
| 22 |
+
import sys
|
| 23 |
+
import threading
|
| 24 |
+
|
| 25 |
+
from . import format_helpers
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Handle:
|
| 29 |
+
"""Object returned by callback registration methods."""
|
| 30 |
+
|
| 31 |
+
__slots__ = ('_callback', '_args', '_cancelled', '_loop',
|
| 32 |
+
'_source_traceback', '_repr', '__weakref__',
|
| 33 |
+
'_context')
|
| 34 |
+
|
| 35 |
+
def __init__(self, callback, args, loop, context=None):
|
| 36 |
+
if context is None:
|
| 37 |
+
context = contextvars.copy_context()
|
| 38 |
+
self._context = context
|
| 39 |
+
self._loop = loop
|
| 40 |
+
self._callback = callback
|
| 41 |
+
self._args = args
|
| 42 |
+
self._cancelled = False
|
| 43 |
+
self._repr = None
|
| 44 |
+
if self._loop.get_debug():
|
| 45 |
+
self._source_traceback = format_helpers.extract_stack(
|
| 46 |
+
sys._getframe(1))
|
| 47 |
+
else:
|
| 48 |
+
self._source_traceback = None
|
| 49 |
+
|
| 50 |
+
def _repr_info(self):
|
| 51 |
+
info = [self.__class__.__name__]
|
| 52 |
+
if self._cancelled:
|
| 53 |
+
info.append('cancelled')
|
| 54 |
+
if self._callback is not None:
|
| 55 |
+
info.append(format_helpers._format_callback_source(
|
| 56 |
+
self._callback, self._args))
|
| 57 |
+
if self._source_traceback:
|
| 58 |
+
frame = self._source_traceback[-1]
|
| 59 |
+
info.append(f'created at {frame[0]}:{frame[1]}')
|
| 60 |
+
return info
|
| 61 |
+
|
| 62 |
+
def __repr__(self):
|
| 63 |
+
if self._repr is not None:
|
| 64 |
+
return self._repr
|
| 65 |
+
info = self._repr_info()
|
| 66 |
+
return '<{}>'.format(' '.join(info))
|
| 67 |
+
|
| 68 |
+
def cancel(self):
|
| 69 |
+
if not self._cancelled:
|
| 70 |
+
self._cancelled = True
|
| 71 |
+
if self._loop.get_debug():
|
| 72 |
+
# Keep a representation in debug mode to keep callback and
|
| 73 |
+
# parameters. For example, to log the warning
|
| 74 |
+
# "Executing <Handle...> took 2.5 second"
|
| 75 |
+
self._repr = repr(self)
|
| 76 |
+
self._callback = None
|
| 77 |
+
self._args = None
|
| 78 |
+
|
| 79 |
+
def cancelled(self):
|
| 80 |
+
return self._cancelled
|
| 81 |
+
|
| 82 |
+
def _run(self):
|
| 83 |
+
try:
|
| 84 |
+
self._context.run(self._callback, *self._args)
|
| 85 |
+
except (SystemExit, KeyboardInterrupt):
|
| 86 |
+
raise
|
| 87 |
+
except BaseException as exc:
|
| 88 |
+
cb = format_helpers._format_callback_source(
|
| 89 |
+
self._callback, self._args)
|
| 90 |
+
msg = f'Exception in callback {cb}'
|
| 91 |
+
context = {
|
| 92 |
+
'message': msg,
|
| 93 |
+
'exception': exc,
|
| 94 |
+
'handle': self,
|
| 95 |
+
}
|
| 96 |
+
if self._source_traceback:
|
| 97 |
+
context['source_traceback'] = self._source_traceback
|
| 98 |
+
self._loop.call_exception_handler(context)
|
| 99 |
+
self = None # Needed to break cycles when an exception occurs.
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class TimerHandle(Handle):
|
| 103 |
+
"""Object returned by timed callback registration methods."""
|
| 104 |
+
|
| 105 |
+
__slots__ = ['_scheduled', '_when']
|
| 106 |
+
|
| 107 |
+
def __init__(self, when, callback, args, loop, context=None):
|
| 108 |
+
super().__init__(callback, args, loop, context)
|
| 109 |
+
if self._source_traceback:
|
| 110 |
+
del self._source_traceback[-1]
|
| 111 |
+
self._when = when
|
| 112 |
+
self._scheduled = False
|
| 113 |
+
|
| 114 |
+
def _repr_info(self):
|
| 115 |
+
info = super()._repr_info()
|
| 116 |
+
pos = 2 if self._cancelled else 1
|
| 117 |
+
info.insert(pos, f'when={self._when}')
|
| 118 |
+
return info
|
| 119 |
+
|
| 120 |
+
def __hash__(self):
|
| 121 |
+
return hash(self._when)
|
| 122 |
+
|
| 123 |
+
def __lt__(self, other):
|
| 124 |
+
if isinstance(other, TimerHandle):
|
| 125 |
+
return self._when < other._when
|
| 126 |
+
return NotImplemented
|
| 127 |
+
|
| 128 |
+
def __le__(self, other):
|
| 129 |
+
if isinstance(other, TimerHandle):
|
| 130 |
+
return self._when < other._when or self.__eq__(other)
|
| 131 |
+
return NotImplemented
|
| 132 |
+
|
| 133 |
+
def __gt__(self, other):
|
| 134 |
+
if isinstance(other, TimerHandle):
|
| 135 |
+
return self._when > other._when
|
| 136 |
+
return NotImplemented
|
| 137 |
+
|
| 138 |
+
def __ge__(self, other):
|
| 139 |
+
if isinstance(other, TimerHandle):
|
| 140 |
+
return self._when > other._when or self.__eq__(other)
|
| 141 |
+
return NotImplemented
|
| 142 |
+
|
| 143 |
+
def __eq__(self, other):
|
| 144 |
+
if isinstance(other, TimerHandle):
|
| 145 |
+
return (self._when == other._when and
|
| 146 |
+
self._callback == other._callback and
|
| 147 |
+
self._args == other._args and
|
| 148 |
+
self._cancelled == other._cancelled)
|
| 149 |
+
return NotImplemented
|
| 150 |
+
|
| 151 |
+
def cancel(self):
|
| 152 |
+
if not self._cancelled:
|
| 153 |
+
self._loop._timer_handle_cancelled(self)
|
| 154 |
+
super().cancel()
|
| 155 |
+
|
| 156 |
+
def when(self):
|
| 157 |
+
"""Return a scheduled callback time.
|
| 158 |
+
|
| 159 |
+
The time is an absolute timestamp, using the same time
|
| 160 |
+
reference as loop.time().
|
| 161 |
+
"""
|
| 162 |
+
return self._when
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class AbstractServer:
|
| 166 |
+
"""Abstract server returned by create_server()."""
|
| 167 |
+
|
| 168 |
+
def close(self):
|
| 169 |
+
"""Stop serving. This leaves existing connections open."""
|
| 170 |
+
raise NotImplementedError
|
| 171 |
+
|
| 172 |
+
def get_loop(self):
|
| 173 |
+
"""Get the event loop the Server object is attached to."""
|
| 174 |
+
raise NotImplementedError
|
| 175 |
+
|
| 176 |
+
def is_serving(self):
|
| 177 |
+
"""Return True if the server is accepting connections."""
|
| 178 |
+
raise NotImplementedError
|
| 179 |
+
|
| 180 |
+
async def start_serving(self):
|
| 181 |
+
"""Start accepting connections.
|
| 182 |
+
|
| 183 |
+
This method is idempotent, so it can be called when
|
| 184 |
+
the server is already being serving.
|
| 185 |
+
"""
|
| 186 |
+
raise NotImplementedError
|
| 187 |
+
|
| 188 |
+
async def serve_forever(self):
|
| 189 |
+
"""Start accepting connections until the coroutine is cancelled.
|
| 190 |
+
|
| 191 |
+
The server is closed when the coroutine is cancelled.
|
| 192 |
+
"""
|
| 193 |
+
raise NotImplementedError
|
| 194 |
+
|
| 195 |
+
async def wait_closed(self):
|
| 196 |
+
"""Coroutine to wait until service is closed."""
|
| 197 |
+
raise NotImplementedError
|
| 198 |
+
|
| 199 |
+
async def __aenter__(self):
|
| 200 |
+
return self
|
| 201 |
+
|
| 202 |
+
async def __aexit__(self, *exc):
|
| 203 |
+
self.close()
|
| 204 |
+
await self.wait_closed()
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
class AbstractEventLoop:
|
| 208 |
+
"""Abstract event loop."""
|
| 209 |
+
|
| 210 |
+
# Running and stopping the event loop.
|
| 211 |
+
|
| 212 |
+
def run_forever(self):
|
| 213 |
+
"""Run the event loop until stop() is called."""
|
| 214 |
+
raise NotImplementedError
|
| 215 |
+
|
| 216 |
+
def run_until_complete(self, future):
|
| 217 |
+
"""Run the event loop until a Future is done.
|
| 218 |
+
|
| 219 |
+
Return the Future's result, or raise its exception.
|
| 220 |
+
"""
|
| 221 |
+
raise NotImplementedError
|
| 222 |
+
|
| 223 |
+
def stop(self):
|
| 224 |
+
"""Stop the event loop as soon as reasonable.
|
| 225 |
+
|
| 226 |
+
Exactly how soon that is may depend on the implementation, but
|
| 227 |
+
no more I/O callbacks should be scheduled.
|
| 228 |
+
"""
|
| 229 |
+
raise NotImplementedError
|
| 230 |
+
|
| 231 |
+
def is_running(self):
|
| 232 |
+
"""Return whether the event loop is currently running."""
|
| 233 |
+
raise NotImplementedError
|
| 234 |
+
|
| 235 |
+
def is_closed(self):
|
| 236 |
+
"""Returns True if the event loop was closed."""
|
| 237 |
+
raise NotImplementedError
|
| 238 |
+
|
| 239 |
+
def close(self):
|
| 240 |
+
"""Close the loop.
|
| 241 |
+
|
| 242 |
+
The loop should not be running.
|
| 243 |
+
|
| 244 |
+
This is idempotent and irreversible.
|
| 245 |
+
|
| 246 |
+
No other methods should be called after this one.
|
| 247 |
+
"""
|
| 248 |
+
raise NotImplementedError
|
| 249 |
+
|
| 250 |
+
async def shutdown_asyncgens(self):
|
| 251 |
+
"""Shutdown all active asynchronous generators."""
|
| 252 |
+
raise NotImplementedError
|
| 253 |
+
|
| 254 |
+
async def shutdown_default_executor(self):
|
| 255 |
+
"""Schedule the shutdown of the default executor."""
|
| 256 |
+
raise NotImplementedError
|
| 257 |
+
|
| 258 |
+
# Methods scheduling callbacks. All these return Handles.
|
| 259 |
+
|
| 260 |
+
def _timer_handle_cancelled(self, handle):
|
| 261 |
+
"""Notification that a TimerHandle has been cancelled."""
|
| 262 |
+
raise NotImplementedError
|
| 263 |
+
|
| 264 |
+
def call_soon(self, callback, *args, context=None):
|
| 265 |
+
return self.call_later(0, callback, *args, context=context)
|
| 266 |
+
|
| 267 |
+
def call_later(self, delay, callback, *args, context=None):
|
| 268 |
+
raise NotImplementedError
|
| 269 |
+
|
| 270 |
+
def call_at(self, when, callback, *args, context=None):
|
| 271 |
+
raise NotImplementedError
|
| 272 |
+
|
| 273 |
+
def time(self):
|
| 274 |
+
raise NotImplementedError
|
| 275 |
+
|
| 276 |
+
def create_future(self):
|
| 277 |
+
raise NotImplementedError
|
| 278 |
+
|
| 279 |
+
# Method scheduling a coroutine object: create a task.
|
| 280 |
+
|
| 281 |
+
def create_task(self, coro, *, name=None, context=None):
|
| 282 |
+
raise NotImplementedError
|
| 283 |
+
|
| 284 |
+
# Methods for interacting with threads.
|
| 285 |
+
|
| 286 |
+
def call_soon_threadsafe(self, callback, *args, context=None):
|
| 287 |
+
raise NotImplementedError
|
| 288 |
+
|
| 289 |
+
def run_in_executor(self, executor, func, *args):
|
| 290 |
+
raise NotImplementedError
|
| 291 |
+
|
| 292 |
+
def set_default_executor(self, executor):
|
| 293 |
+
raise NotImplementedError
|
| 294 |
+
|
| 295 |
+
# Network I/O methods returning Futures.
|
| 296 |
+
|
| 297 |
+
async def getaddrinfo(self, host, port, *,
|
| 298 |
+
family=0, type=0, proto=0, flags=0):
|
| 299 |
+
raise NotImplementedError
|
| 300 |
+
|
| 301 |
+
async def getnameinfo(self, sockaddr, flags=0):
|
| 302 |
+
raise NotImplementedError
|
| 303 |
+
|
| 304 |
+
async def create_connection(
|
| 305 |
+
self, protocol_factory, host=None, port=None,
|
| 306 |
+
*, ssl=None, family=0, proto=0,
|
| 307 |
+
flags=0, sock=None, local_addr=None,
|
| 308 |
+
server_hostname=None,
|
| 309 |
+
ssl_handshake_timeout=None,
|
| 310 |
+
ssl_shutdown_timeout=None,
|
| 311 |
+
happy_eyeballs_delay=None, interleave=None):
|
| 312 |
+
raise NotImplementedError
|
| 313 |
+
|
| 314 |
+
async def create_server(
|
| 315 |
+
self, protocol_factory, host=None, port=None,
|
| 316 |
+
*, family=socket.AF_UNSPEC,
|
| 317 |
+
flags=socket.AI_PASSIVE, sock=None, backlog=100,
|
| 318 |
+
ssl=None, reuse_address=None, reuse_port=None,
|
| 319 |
+
ssl_handshake_timeout=None,
|
| 320 |
+
ssl_shutdown_timeout=None,
|
| 321 |
+
start_serving=True):
|
| 322 |
+
"""A coroutine which creates a TCP server bound to host and port.
|
| 323 |
+
|
| 324 |
+
The return value is a Server object which can be used to stop
|
| 325 |
+
the service.
|
| 326 |
+
|
| 327 |
+
If host is an empty string or None all interfaces are assumed
|
| 328 |
+
and a list of multiple sockets will be returned (most likely
|
| 329 |
+
one for IPv4 and another one for IPv6). The host parameter can also be
|
| 330 |
+
a sequence (e.g. list) of hosts to bind to.
|
| 331 |
+
|
| 332 |
+
family can be set to either AF_INET or AF_INET6 to force the
|
| 333 |
+
socket to use IPv4 or IPv6. If not set it will be determined
|
| 334 |
+
from host (defaults to AF_UNSPEC).
|
| 335 |
+
|
| 336 |
+
flags is a bitmask for getaddrinfo().
|
| 337 |
+
|
| 338 |
+
sock can optionally be specified in order to use a preexisting
|
| 339 |
+
socket object.
|
| 340 |
+
|
| 341 |
+
backlog is the maximum number of queued connections passed to
|
| 342 |
+
listen() (defaults to 100).
|
| 343 |
+
|
| 344 |
+
ssl can be set to an SSLContext to enable SSL over the
|
| 345 |
+
accepted connections.
|
| 346 |
+
|
| 347 |
+
reuse_address tells the kernel to reuse a local socket in
|
| 348 |
+
TIME_WAIT state, without waiting for its natural timeout to
|
| 349 |
+
expire. If not specified will automatically be set to True on
|
| 350 |
+
UNIX.
|
| 351 |
+
|
| 352 |
+
reuse_port tells the kernel to allow this endpoint to be bound to
|
| 353 |
+
the same port as other existing endpoints are bound to, so long as
|
| 354 |
+
they all set this flag when being created. This option is not
|
| 355 |
+
supported on Windows.
|
| 356 |
+
|
| 357 |
+
ssl_handshake_timeout is the time in seconds that an SSL server
|
| 358 |
+
will wait for completion of the SSL handshake before aborting the
|
| 359 |
+
connection. Default is 60s.
|
| 360 |
+
|
| 361 |
+
ssl_shutdown_timeout is the time in seconds that an SSL server
|
| 362 |
+
will wait for completion of the SSL shutdown procedure
|
| 363 |
+
before aborting the connection. Default is 30s.
|
| 364 |
+
|
| 365 |
+
start_serving set to True (default) causes the created server
|
| 366 |
+
to start accepting connections immediately. When set to False,
|
| 367 |
+
the user should await Server.start_serving() or Server.serve_forever()
|
| 368 |
+
to make the server to start accepting connections.
|
| 369 |
+
"""
|
| 370 |
+
raise NotImplementedError
|
| 371 |
+
|
| 372 |
+
async def sendfile(self, transport, file, offset=0, count=None,
|
| 373 |
+
*, fallback=True):
|
| 374 |
+
"""Send a file through a transport.
|
| 375 |
+
|
| 376 |
+
Return an amount of sent bytes.
|
| 377 |
+
"""
|
| 378 |
+
raise NotImplementedError
|
| 379 |
+
|
| 380 |
+
async def start_tls(self, transport, protocol, sslcontext, *,
|
| 381 |
+
server_side=False,
|
| 382 |
+
server_hostname=None,
|
| 383 |
+
ssl_handshake_timeout=None,
|
| 384 |
+
ssl_shutdown_timeout=None):
|
| 385 |
+
"""Upgrade a transport to TLS.
|
| 386 |
+
|
| 387 |
+
Return a new transport that *protocol* should start using
|
| 388 |
+
immediately.
|
| 389 |
+
"""
|
| 390 |
+
raise NotImplementedError
|
| 391 |
+
|
| 392 |
+
async def create_unix_connection(
|
| 393 |
+
self, protocol_factory, path=None, *,
|
| 394 |
+
ssl=None, sock=None,
|
| 395 |
+
server_hostname=None,
|
| 396 |
+
ssl_handshake_timeout=None,
|
| 397 |
+
ssl_shutdown_timeout=None):
|
| 398 |
+
raise NotImplementedError
|
| 399 |
+
|
| 400 |
+
async def create_unix_server(
|
| 401 |
+
self, protocol_factory, path=None, *,
|
| 402 |
+
sock=None, backlog=100, ssl=None,
|
| 403 |
+
ssl_handshake_timeout=None,
|
| 404 |
+
ssl_shutdown_timeout=None,
|
| 405 |
+
start_serving=True):
|
| 406 |
+
"""A coroutine which creates a UNIX Domain Socket server.
|
| 407 |
+
|
| 408 |
+
The return value is a Server object, which can be used to stop
|
| 409 |
+
the service.
|
| 410 |
+
|
| 411 |
+
path is a str, representing a file system path to bind the
|
| 412 |
+
server socket to.
|
| 413 |
+
|
| 414 |
+
sock can optionally be specified in order to use a preexisting
|
| 415 |
+
socket object.
|
| 416 |
+
|
| 417 |
+
backlog is the maximum number of queued connections passed to
|
| 418 |
+
listen() (defaults to 100).
|
| 419 |
+
|
| 420 |
+
ssl can be set to an SSLContext to enable SSL over the
|
| 421 |
+
accepted connections.
|
| 422 |
+
|
| 423 |
+
ssl_handshake_timeout is the time in seconds that an SSL server
|
| 424 |
+
will wait for the SSL handshake to complete (defaults to 60s).
|
| 425 |
+
|
| 426 |
+
ssl_shutdown_timeout is the time in seconds that an SSL server
|
| 427 |
+
will wait for the SSL shutdown to finish (defaults to 30s).
|
| 428 |
+
|
| 429 |
+
start_serving set to True (default) causes the created server
|
| 430 |
+
to start accepting connections immediately. When set to False,
|
| 431 |
+
the user should await Server.start_serving() or Server.serve_forever()
|
| 432 |
+
to make the server to start accepting connections.
|
| 433 |
+
"""
|
| 434 |
+
raise NotImplementedError
|
| 435 |
+
|
| 436 |
+
async def connect_accepted_socket(
|
| 437 |
+
self, protocol_factory, sock,
|
| 438 |
+
*, ssl=None,
|
| 439 |
+
ssl_handshake_timeout=None,
|
| 440 |
+
ssl_shutdown_timeout=None):
|
| 441 |
+
"""Handle an accepted connection.
|
| 442 |
+
|
| 443 |
+
This is used by servers that accept connections outside of
|
| 444 |
+
asyncio, but use asyncio to handle connections.
|
| 445 |
+
|
| 446 |
+
This method is a coroutine. When completed, the coroutine
|
| 447 |
+
returns a (transport, protocol) pair.
|
| 448 |
+
"""
|
| 449 |
+
raise NotImplementedError
|
| 450 |
+
|
| 451 |
+
async def create_datagram_endpoint(self, protocol_factory,
|
| 452 |
+
local_addr=None, remote_addr=None, *,
|
| 453 |
+
family=0, proto=0, flags=0,
|
| 454 |
+
reuse_address=None, reuse_port=None,
|
| 455 |
+
allow_broadcast=None, sock=None):
|
| 456 |
+
"""A coroutine which creates a datagram endpoint.
|
| 457 |
+
|
| 458 |
+
This method will try to establish the endpoint in the background.
|
| 459 |
+
When successful, the coroutine returns a (transport, protocol) pair.
|
| 460 |
+
|
| 461 |
+
protocol_factory must be a callable returning a protocol instance.
|
| 462 |
+
|
| 463 |
+
socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
|
| 464 |
+
host (or family if specified), socket type SOCK_DGRAM.
|
| 465 |
+
|
| 466 |
+
reuse_address tells the kernel to reuse a local socket in
|
| 467 |
+
TIME_WAIT state, without waiting for its natural timeout to
|
| 468 |
+
expire. If not specified it will automatically be set to True on
|
| 469 |
+
UNIX.
|
| 470 |
+
|
| 471 |
+
reuse_port tells the kernel to allow this endpoint to be bound to
|
| 472 |
+
the same port as other existing endpoints are bound to, so long as
|
| 473 |
+
they all set this flag when being created. This option is not
|
| 474 |
+
supported on Windows and some UNIX's. If the
|
| 475 |
+
:py:data:`~socket.SO_REUSEPORT` constant is not defined then this
|
| 476 |
+
capability is unsupported.
|
| 477 |
+
|
| 478 |
+
allow_broadcast tells the kernel to allow this endpoint to send
|
| 479 |
+
messages to the broadcast address.
|
| 480 |
+
|
| 481 |
+
sock can optionally be specified in order to use a preexisting
|
| 482 |
+
socket object.
|
| 483 |
+
"""
|
| 484 |
+
raise NotImplementedError
|
| 485 |
+
|
| 486 |
+
# Pipes and subprocesses.
|
| 487 |
+
|
| 488 |
+
async def connect_read_pipe(self, protocol_factory, pipe):
|
| 489 |
+
"""Register read pipe in event loop. Set the pipe to non-blocking mode.
|
| 490 |
+
|
| 491 |
+
protocol_factory should instantiate object with Protocol interface.
|
| 492 |
+
pipe is a file-like object.
|
| 493 |
+
Return pair (transport, protocol), where transport supports the
|
| 494 |
+
ReadTransport interface."""
|
| 495 |
+
# The reason to accept file-like object instead of just file descriptor
|
| 496 |
+
# is: we need to own pipe and close it at transport finishing
|
| 497 |
+
# Can got complicated errors if pass f.fileno(),
|
| 498 |
+
# close fd in pipe transport then close f and vice versa.
|
| 499 |
+
raise NotImplementedError
|
| 500 |
+
|
| 501 |
+
async def connect_write_pipe(self, protocol_factory, pipe):
|
| 502 |
+
"""Register write pipe in event loop.
|
| 503 |
+
|
| 504 |
+
protocol_factory should instantiate object with BaseProtocol interface.
|
| 505 |
+
Pipe is file-like object already switched to nonblocking.
|
| 506 |
+
Return pair (transport, protocol), where transport support
|
| 507 |
+
WriteTransport interface."""
|
| 508 |
+
# The reason to accept file-like object instead of just file descriptor
|
| 509 |
+
# is: we need to own pipe and close it at transport finishing
|
| 510 |
+
# Can got complicated errors if pass f.fileno(),
|
| 511 |
+
# close fd in pipe transport then close f and vice versa.
|
| 512 |
+
raise NotImplementedError
|
| 513 |
+
|
| 514 |
+
async def subprocess_shell(self, protocol_factory, cmd, *,
|
| 515 |
+
stdin=subprocess.PIPE,
|
| 516 |
+
stdout=subprocess.PIPE,
|
| 517 |
+
stderr=subprocess.PIPE,
|
| 518 |
+
**kwargs):
|
| 519 |
+
raise NotImplementedError
|
| 520 |
+
|
| 521 |
+
async def subprocess_exec(self, protocol_factory, *args,
|
| 522 |
+
stdin=subprocess.PIPE,
|
| 523 |
+
stdout=subprocess.PIPE,
|
| 524 |
+
stderr=subprocess.PIPE,
|
| 525 |
+
**kwargs):
|
| 526 |
+
raise NotImplementedError
|
| 527 |
+
|
| 528 |
+
# Ready-based callback registration methods.
|
| 529 |
+
# The add_*() methods return None.
|
| 530 |
+
# The remove_*() methods return True if something was removed,
|
| 531 |
+
# False if there was nothing to delete.
|
| 532 |
+
|
| 533 |
+
def add_reader(self, fd, callback, *args):
|
| 534 |
+
raise NotImplementedError
|
| 535 |
+
|
| 536 |
+
def remove_reader(self, fd):
|
| 537 |
+
raise NotImplementedError
|
| 538 |
+
|
| 539 |
+
def add_writer(self, fd, callback, *args):
|
| 540 |
+
raise NotImplementedError
|
| 541 |
+
|
| 542 |
+
def remove_writer(self, fd):
|
| 543 |
+
raise NotImplementedError
|
| 544 |
+
|
| 545 |
+
# Completion based I/O methods returning Futures.
|
| 546 |
+
|
| 547 |
+
async def sock_recv(self, sock, nbytes):
|
| 548 |
+
raise NotImplementedError
|
| 549 |
+
|
| 550 |
+
async def sock_recv_into(self, sock, buf):
|
| 551 |
+
raise NotImplementedError
|
| 552 |
+
|
| 553 |
+
async def sock_recvfrom(self, sock, bufsize):
|
| 554 |
+
raise NotImplementedError
|
| 555 |
+
|
| 556 |
+
async def sock_recvfrom_into(self, sock, buf, nbytes=0):
|
| 557 |
+
raise NotImplementedError
|
| 558 |
+
|
| 559 |
+
async def sock_sendall(self, sock, data):
|
| 560 |
+
raise NotImplementedError
|
| 561 |
+
|
| 562 |
+
async def sock_sendto(self, sock, data, address):
|
| 563 |
+
raise NotImplementedError
|
| 564 |
+
|
| 565 |
+
async def sock_connect(self, sock, address):
|
| 566 |
+
raise NotImplementedError
|
| 567 |
+
|
| 568 |
+
async def sock_accept(self, sock):
|
| 569 |
+
raise NotImplementedError
|
| 570 |
+
|
| 571 |
+
async def sock_sendfile(self, sock, file, offset=0, count=None,
|
| 572 |
+
*, fallback=None):
|
| 573 |
+
raise NotImplementedError
|
| 574 |
+
|
| 575 |
+
# Signal handling.
|
| 576 |
+
|
| 577 |
+
def add_signal_handler(self, sig, callback, *args):
|
| 578 |
+
raise NotImplementedError
|
| 579 |
+
|
| 580 |
+
def remove_signal_handler(self, sig):
|
| 581 |
+
raise NotImplementedError
|
| 582 |
+
|
| 583 |
+
# Task factory.
|
| 584 |
+
|
| 585 |
+
def set_task_factory(self, factory):
|
| 586 |
+
raise NotImplementedError
|
| 587 |
+
|
| 588 |
+
def get_task_factory(self):
|
| 589 |
+
raise NotImplementedError
|
| 590 |
+
|
| 591 |
+
# Error handlers.
|
| 592 |
+
|
| 593 |
+
def get_exception_handler(self):
|
| 594 |
+
raise NotImplementedError
|
| 595 |
+
|
| 596 |
+
def set_exception_handler(self, handler):
|
| 597 |
+
raise NotImplementedError
|
| 598 |
+
|
| 599 |
+
def default_exception_handler(self, context):
|
| 600 |
+
raise NotImplementedError
|
| 601 |
+
|
| 602 |
+
def call_exception_handler(self, context):
|
| 603 |
+
raise NotImplementedError
|
| 604 |
+
|
| 605 |
+
# Debug flag management.
|
| 606 |
+
|
| 607 |
+
def get_debug(self):
|
| 608 |
+
raise NotImplementedError
|
| 609 |
+
|
| 610 |
+
def set_debug(self, enabled):
|
| 611 |
+
raise NotImplementedError
|
| 612 |
+
|
| 613 |
+
|
| 614 |
+
class AbstractEventLoopPolicy:
|
| 615 |
+
"""Abstract policy for accessing the event loop."""
|
| 616 |
+
|
| 617 |
+
def get_event_loop(self):
|
| 618 |
+
"""Get the event loop for the current context.
|
| 619 |
+
|
| 620 |
+
Returns an event loop object implementing the AbstractEventLoop interface,
|
| 621 |
+
or raises an exception in case no event loop has been set for the
|
| 622 |
+
current context and the current policy does not specify to create one.
|
| 623 |
+
|
| 624 |
+
It should never return None."""
|
| 625 |
+
raise NotImplementedError
|
| 626 |
+
|
| 627 |
+
def set_event_loop(self, loop):
|
| 628 |
+
"""Set the event loop for the current context to loop."""
|
| 629 |
+
raise NotImplementedError
|
| 630 |
+
|
| 631 |
+
def new_event_loop(self):
|
| 632 |
+
"""Create and return a new event loop object according to this
|
| 633 |
+
policy's rules. If there's need to set this loop as the event loop for
|
| 634 |
+
the current context, set_event_loop must be called explicitly."""
|
| 635 |
+
raise NotImplementedError
|
| 636 |
+
|
| 637 |
+
# Child processes handling (Unix only).
|
| 638 |
+
|
| 639 |
+
def get_child_watcher(self):
|
| 640 |
+
"Get the watcher for child processes."
|
| 641 |
+
raise NotImplementedError
|
| 642 |
+
|
| 643 |
+
def set_child_watcher(self, watcher):
|
| 644 |
+
"""Set the watcher for child processes."""
|
| 645 |
+
raise NotImplementedError
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
|
| 649 |
+
"""Default policy implementation for accessing the event loop.
|
| 650 |
+
|
| 651 |
+
In this policy, each thread has its own event loop. However, we
|
| 652 |
+
only automatically create an event loop by default for the main
|
| 653 |
+
thread; other threads by default have no event loop.
|
| 654 |
+
|
| 655 |
+
Other policies may have different rules (e.g. a single global
|
| 656 |
+
event loop, or automatically creating an event loop per thread, or
|
| 657 |
+
using some other notion of context to which an event loop is
|
| 658 |
+
associated).
|
| 659 |
+
"""
|
| 660 |
+
|
| 661 |
+
_loop_factory = None
|
| 662 |
+
|
| 663 |
+
class _Local(threading.local):
|
| 664 |
+
_loop = None
|
| 665 |
+
_set_called = False
|
| 666 |
+
|
| 667 |
+
def __init__(self):
|
| 668 |
+
self._local = self._Local()
|
| 669 |
+
|
| 670 |
+
def get_event_loop(self):
|
| 671 |
+
"""Get the event loop for the current context.
|
| 672 |
+
|
| 673 |
+
Returns an instance of EventLoop or raises an exception.
|
| 674 |
+
"""
|
| 675 |
+
if (self._local._loop is None and
|
| 676 |
+
not self._local._set_called and
|
| 677 |
+
threading.current_thread() is threading.main_thread()):
|
| 678 |
+
self.set_event_loop(self.new_event_loop())
|
| 679 |
+
|
| 680 |
+
if self._local._loop is None:
|
| 681 |
+
raise RuntimeError('There is no current event loop in thread %r.'
|
| 682 |
+
% threading.current_thread().name)
|
| 683 |
+
|
| 684 |
+
return self._local._loop
|
| 685 |
+
|
| 686 |
+
def set_event_loop(self, loop):
|
| 687 |
+
"""Set the event loop."""
|
| 688 |
+
self._local._set_called = True
|
| 689 |
+
if loop is not None and not isinstance(loop, AbstractEventLoop):
|
| 690 |
+
raise TypeError(f"loop must be an instance of AbstractEventLoop or None, not '{type(loop).__name__}'")
|
| 691 |
+
self._local._loop = loop
|
| 692 |
+
|
| 693 |
+
def new_event_loop(self):
|
| 694 |
+
"""Create a new event loop.
|
| 695 |
+
|
| 696 |
+
You must call set_event_loop() to make this the current event
|
| 697 |
+
loop.
|
| 698 |
+
"""
|
| 699 |
+
return self._loop_factory()
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
# Event loop policy. The policy itself is always global, even if the
|
| 703 |
+
# policy's rules say that there is an event loop per thread (or other
|
| 704 |
+
# notion of context). The default policy is installed by the first
|
| 705 |
+
# call to get_event_loop_policy().
|
| 706 |
+
_event_loop_policy = None
|
| 707 |
+
|
| 708 |
+
# Lock for protecting the on-the-fly creation of the event loop policy.
|
| 709 |
+
_lock = threading.Lock()
|
| 710 |
+
|
| 711 |
+
|
| 712 |
+
# A TLS for the running event loop, used by _get_running_loop.
|
| 713 |
+
class _RunningLoop(threading.local):
|
| 714 |
+
loop_pid = (None, None)
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
_running_loop = _RunningLoop()
|
| 718 |
+
|
| 719 |
+
|
| 720 |
+
def get_running_loop():
|
| 721 |
+
"""Return the running event loop. Raise a RuntimeError if there is none.
|
| 722 |
+
|
| 723 |
+
This function is thread-specific.
|
| 724 |
+
"""
|
| 725 |
+
# NOTE: this function is implemented in C (see _asynciomodule.c)
|
| 726 |
+
loop = _get_running_loop()
|
| 727 |
+
if loop is None:
|
| 728 |
+
raise RuntimeError('no running event loop')
|
| 729 |
+
return loop
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def _get_running_loop():
|
| 733 |
+
"""Return the running event loop or None.
|
| 734 |
+
|
| 735 |
+
This is a low-level function intended to be used by event loops.
|
| 736 |
+
This function is thread-specific.
|
| 737 |
+
"""
|
| 738 |
+
# NOTE: this function is implemented in C (see _asynciomodule.c)
|
| 739 |
+
running_loop, pid = _running_loop.loop_pid
|
| 740 |
+
if running_loop is not None and pid == os.getpid():
|
| 741 |
+
return running_loop
|
| 742 |
+
|
| 743 |
+
|
| 744 |
+
def _set_running_loop(loop):
|
| 745 |
+
"""Set the running event loop.
|
| 746 |
+
|
| 747 |
+
This is a low-level function intended to be used by event loops.
|
| 748 |
+
This function is thread-specific.
|
| 749 |
+
"""
|
| 750 |
+
# NOTE: this function is implemented in C (see _asynciomodule.c)
|
| 751 |
+
_running_loop.loop_pid = (loop, os.getpid())
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
def _init_event_loop_policy():
|
| 755 |
+
global _event_loop_policy
|
| 756 |
+
with _lock:
|
| 757 |
+
if _event_loop_policy is None: # pragma: no branch
|
| 758 |
+
from . import DefaultEventLoopPolicy
|
| 759 |
+
_event_loop_policy = DefaultEventLoopPolicy()
|
| 760 |
+
|
| 761 |
+
|
| 762 |
+
def get_event_loop_policy():
|
| 763 |
+
"""Get the current event loop policy."""
|
| 764 |
+
if _event_loop_policy is None:
|
| 765 |
+
_init_event_loop_policy()
|
| 766 |
+
return _event_loop_policy
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
def set_event_loop_policy(policy):
|
| 770 |
+
"""Set the current event loop policy.
|
| 771 |
+
|
| 772 |
+
If policy is None, the default policy is restored."""
|
| 773 |
+
global _event_loop_policy
|
| 774 |
+
if policy is not None and not isinstance(policy, AbstractEventLoopPolicy):
|
| 775 |
+
raise TypeError(f"policy must be an instance of AbstractEventLoopPolicy or None, not '{type(policy).__name__}'")
|
| 776 |
+
_event_loop_policy = policy
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
def get_event_loop():
|
| 780 |
+
"""Return an asyncio event loop.
|
| 781 |
+
|
| 782 |
+
When called from a coroutine or a callback (e.g. scheduled with call_soon
|
| 783 |
+
or similar API), this function will always return the running event loop.
|
| 784 |
+
|
| 785 |
+
If there is no running event loop set, the function will return
|
| 786 |
+
the result of `get_event_loop_policy().get_event_loop()` call.
|
| 787 |
+
"""
|
| 788 |
+
# NOTE: this function is implemented in C (see _asynciomodule.c)
|
| 789 |
+
return _py__get_event_loop()
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
def _get_event_loop(stacklevel=3):
|
| 793 |
+
# This internal method is going away in Python 3.12, left here only for
|
| 794 |
+
# backwards compatibility with 3.10.0 - 3.10.8 and 3.11.0.
|
| 795 |
+
# Similarly, this method's C equivalent in _asyncio is going away as well.
|
| 796 |
+
# See GH-99949 for more details.
|
| 797 |
+
current_loop = _get_running_loop()
|
| 798 |
+
if current_loop is not None:
|
| 799 |
+
return current_loop
|
| 800 |
+
return get_event_loop_policy().get_event_loop()
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
def set_event_loop(loop):
|
| 804 |
+
"""Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
|
| 805 |
+
get_event_loop_policy().set_event_loop(loop)
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def new_event_loop():
|
| 809 |
+
"""Equivalent to calling get_event_loop_policy().new_event_loop()."""
|
| 810 |
+
return get_event_loop_policy().new_event_loop()
|
| 811 |
+
|
| 812 |
+
|
| 813 |
+
def get_child_watcher():
|
| 814 |
+
"""Equivalent to calling get_event_loop_policy().get_child_watcher()."""
|
| 815 |
+
return get_event_loop_policy().get_child_watcher()
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
def set_child_watcher(watcher):
|
| 819 |
+
"""Equivalent to calling
|
| 820 |
+
get_event_loop_policy().set_child_watcher(watcher)."""
|
| 821 |
+
return get_event_loop_policy().set_child_watcher(watcher)
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
# Alias pure-Python implementations for testing purposes.
|
| 825 |
+
_py__get_running_loop = _get_running_loop
|
| 826 |
+
_py__set_running_loop = _set_running_loop
|
| 827 |
+
_py_get_running_loop = get_running_loop
|
| 828 |
+
_py_get_event_loop = get_event_loop
|
| 829 |
+
_py__get_event_loop = _get_event_loop
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
try:
|
| 833 |
+
# get_event_loop() is one of the most frequently called
|
| 834 |
+
# functions in asyncio. Pure Python implementation is
|
| 835 |
+
# about 4 times slower than C-accelerated.
|
| 836 |
+
from _asyncio import (_get_running_loop, _set_running_loop,
|
| 837 |
+
get_running_loop, get_event_loop, _get_event_loop)
|
| 838 |
+
except ImportError:
|
| 839 |
+
pass
|
| 840 |
+
else:
|
| 841 |
+
# Alias C implementations for testing purposes.
|
| 842 |
+
_c__get_running_loop = _get_running_loop
|
| 843 |
+
_c__set_running_loop = _set_running_loop
|
| 844 |
+
_c_get_running_loop = get_running_loop
|
| 845 |
+
_c_get_event_loop = get_event_loop
|
| 846 |
+
_c__get_event_loop = _get_event_loop
|
micromamba_root/envs/pytorch_env/Lib/asyncio/exceptions.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""asyncio exceptions."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__all__ = ('BrokenBarrierError',
|
| 5 |
+
'CancelledError', 'InvalidStateError', 'TimeoutError',
|
| 6 |
+
'IncompleteReadError', 'LimitOverrunError',
|
| 7 |
+
'SendfileNotAvailableError')
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class CancelledError(BaseException):
|
| 11 |
+
"""The Future or Task was cancelled."""
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
TimeoutError = TimeoutError # make local alias for the standard exception
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class InvalidStateError(Exception):
|
| 18 |
+
"""The operation is not allowed in this state."""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SendfileNotAvailableError(RuntimeError):
|
| 22 |
+
"""Sendfile syscall is not available.
|
| 23 |
+
|
| 24 |
+
Raised if OS does not support sendfile syscall for given socket or
|
| 25 |
+
file type.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class IncompleteReadError(EOFError):
|
| 30 |
+
"""
|
| 31 |
+
Incomplete read error. Attributes:
|
| 32 |
+
|
| 33 |
+
- partial: read bytes string before the end of stream was reached
|
| 34 |
+
- expected: total number of expected bytes (or None if unknown)
|
| 35 |
+
"""
|
| 36 |
+
def __init__(self, partial, expected):
|
| 37 |
+
r_expected = 'undefined' if expected is None else repr(expected)
|
| 38 |
+
super().__init__(f'{len(partial)} bytes read on a total of '
|
| 39 |
+
f'{r_expected} expected bytes')
|
| 40 |
+
self.partial = partial
|
| 41 |
+
self.expected = expected
|
| 42 |
+
|
| 43 |
+
def __reduce__(self):
|
| 44 |
+
return type(self), (self.partial, self.expected)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class LimitOverrunError(Exception):
|
| 48 |
+
"""Reached the buffer limit while looking for a separator.
|
| 49 |
+
|
| 50 |
+
Attributes:
|
| 51 |
+
- consumed: total number of to be consumed bytes.
|
| 52 |
+
"""
|
| 53 |
+
def __init__(self, message, consumed):
|
| 54 |
+
super().__init__(message)
|
| 55 |
+
self.consumed = consumed
|
| 56 |
+
|
| 57 |
+
def __reduce__(self):
|
| 58 |
+
return type(self), (self.args[0], self.consumed)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class BrokenBarrierError(RuntimeError):
|
| 62 |
+
"""Barrier is broken by barrier.abort() call."""
|
micromamba_root/envs/pytorch_env/Lib/asyncio/format_helpers.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import functools
|
| 2 |
+
import inspect
|
| 3 |
+
import reprlib
|
| 4 |
+
import sys
|
| 5 |
+
import traceback
|
| 6 |
+
|
| 7 |
+
from . import constants
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _get_function_source(func):
|
| 11 |
+
func = inspect.unwrap(func)
|
| 12 |
+
if inspect.isfunction(func):
|
| 13 |
+
code = func.__code__
|
| 14 |
+
return (code.co_filename, code.co_firstlineno)
|
| 15 |
+
if isinstance(func, functools.partial):
|
| 16 |
+
return _get_function_source(func.func)
|
| 17 |
+
if isinstance(func, functools.partialmethod):
|
| 18 |
+
return _get_function_source(func.func)
|
| 19 |
+
return None
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _format_callback_source(func, args):
|
| 23 |
+
func_repr = _format_callback(func, args, None)
|
| 24 |
+
source = _get_function_source(func)
|
| 25 |
+
if source:
|
| 26 |
+
func_repr += f' at {source[0]}:{source[1]}'
|
| 27 |
+
return func_repr
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _format_args_and_kwargs(args, kwargs):
|
| 31 |
+
"""Format function arguments and keyword arguments.
|
| 32 |
+
|
| 33 |
+
Special case for a single parameter: ('hello',) is formatted as ('hello').
|
| 34 |
+
"""
|
| 35 |
+
# use reprlib to limit the length of the output
|
| 36 |
+
items = []
|
| 37 |
+
if args:
|
| 38 |
+
items.extend(reprlib.repr(arg) for arg in args)
|
| 39 |
+
if kwargs:
|
| 40 |
+
items.extend(f'{k}={reprlib.repr(v)}' for k, v in kwargs.items())
|
| 41 |
+
return '({})'.format(', '.join(items))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _format_callback(func, args, kwargs, suffix=''):
|
| 45 |
+
if isinstance(func, functools.partial):
|
| 46 |
+
suffix = _format_args_and_kwargs(args, kwargs) + suffix
|
| 47 |
+
return _format_callback(func.func, func.args, func.keywords, suffix)
|
| 48 |
+
|
| 49 |
+
if hasattr(func, '__qualname__') and func.__qualname__:
|
| 50 |
+
func_repr = func.__qualname__
|
| 51 |
+
elif hasattr(func, '__name__') and func.__name__:
|
| 52 |
+
func_repr = func.__name__
|
| 53 |
+
else:
|
| 54 |
+
func_repr = repr(func)
|
| 55 |
+
|
| 56 |
+
func_repr += _format_args_and_kwargs(args, kwargs)
|
| 57 |
+
if suffix:
|
| 58 |
+
func_repr += suffix
|
| 59 |
+
return func_repr
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def extract_stack(f=None, limit=None):
|
| 63 |
+
"""Replacement for traceback.extract_stack() that only does the
|
| 64 |
+
necessary work for asyncio debug mode.
|
| 65 |
+
"""
|
| 66 |
+
if f is None:
|
| 67 |
+
f = sys._getframe().f_back
|
| 68 |
+
if limit is None:
|
| 69 |
+
# Limit the amount of work to a reasonable amount, as extract_stack()
|
| 70 |
+
# can be called for each coroutine and future in debug mode.
|
| 71 |
+
limit = constants.DEBUG_STACK_DEPTH
|
| 72 |
+
stack = traceback.StackSummary.extract(traceback.walk_stack(f),
|
| 73 |
+
limit=limit,
|
| 74 |
+
lookup_lines=False)
|
| 75 |
+
stack.reverse()
|
| 76 |
+
return stack
|
micromamba_root/envs/pytorch_env/Lib/asyncio/futures.py
ADDED
|
@@ -0,0 +1,428 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A Future class similar to the one in PEP 3148."""
|
| 2 |
+
|
| 3 |
+
__all__ = (
|
| 4 |
+
'Future', 'wrap_future', 'isfuture',
|
| 5 |
+
)
|
| 6 |
+
|
| 7 |
+
import concurrent.futures
|
| 8 |
+
import contextvars
|
| 9 |
+
import logging
|
| 10 |
+
import sys
|
| 11 |
+
from types import GenericAlias
|
| 12 |
+
|
| 13 |
+
from . import base_futures
|
| 14 |
+
from . import events
|
| 15 |
+
from . import exceptions
|
| 16 |
+
from . import format_helpers
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
isfuture = base_futures.isfuture
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
_PENDING = base_futures._PENDING
|
| 23 |
+
_CANCELLED = base_futures._CANCELLED
|
| 24 |
+
_FINISHED = base_futures._FINISHED
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
STACK_DEBUG = logging.DEBUG - 1 # heavy-duty debugging
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class Future:
|
| 31 |
+
"""This class is *almost* compatible with concurrent.futures.Future.
|
| 32 |
+
|
| 33 |
+
Differences:
|
| 34 |
+
|
| 35 |
+
- This class is not thread-safe.
|
| 36 |
+
|
| 37 |
+
- result() and exception() do not take a timeout argument and
|
| 38 |
+
raise an exception when the future isn't done yet.
|
| 39 |
+
|
| 40 |
+
- Callbacks registered with add_done_callback() are always called
|
| 41 |
+
via the event loop's call_soon().
|
| 42 |
+
|
| 43 |
+
- This class is not compatible with the wait() and as_completed()
|
| 44 |
+
methods in the concurrent.futures package.
|
| 45 |
+
|
| 46 |
+
(In Python 3.4 or later we may be able to unify the implementations.)
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
# Class variables serving as defaults for instance variables.
|
| 50 |
+
_state = _PENDING
|
| 51 |
+
_result = None
|
| 52 |
+
_exception = None
|
| 53 |
+
_loop = None
|
| 54 |
+
_source_traceback = None
|
| 55 |
+
_cancel_message = None
|
| 56 |
+
# A saved CancelledError for later chaining as an exception context.
|
| 57 |
+
_cancelled_exc = None
|
| 58 |
+
|
| 59 |
+
# This field is used for a dual purpose:
|
| 60 |
+
# - Its presence is a marker to declare that a class implements
|
| 61 |
+
# the Future protocol (i.e. is intended to be duck-type compatible).
|
| 62 |
+
# The value must also be not-None, to enable a subclass to declare
|
| 63 |
+
# that it is not compatible by setting this to None.
|
| 64 |
+
# - It is set by __iter__() below so that Task._step() can tell
|
| 65 |
+
# the difference between
|
| 66 |
+
# `await Future()` or`yield from Future()` (correct) vs.
|
| 67 |
+
# `yield Future()` (incorrect).
|
| 68 |
+
_asyncio_future_blocking = False
|
| 69 |
+
|
| 70 |
+
__log_traceback = False
|
| 71 |
+
|
| 72 |
+
def __init__(self, *, loop=None):
|
| 73 |
+
"""Initialize the future.
|
| 74 |
+
|
| 75 |
+
The optional event_loop argument allows explicitly setting the event
|
| 76 |
+
loop object used by the future. If it's not provided, the future uses
|
| 77 |
+
the default event loop.
|
| 78 |
+
"""
|
| 79 |
+
if loop is None:
|
| 80 |
+
self._loop = events._get_event_loop()
|
| 81 |
+
else:
|
| 82 |
+
self._loop = loop
|
| 83 |
+
self._callbacks = []
|
| 84 |
+
if self._loop.get_debug():
|
| 85 |
+
self._source_traceback = format_helpers.extract_stack(
|
| 86 |
+
sys._getframe(1))
|
| 87 |
+
|
| 88 |
+
def __repr__(self):
|
| 89 |
+
return base_futures._future_repr(self)
|
| 90 |
+
|
| 91 |
+
def __del__(self):
|
| 92 |
+
if not self.__log_traceback:
|
| 93 |
+
# set_exception() was not called, or result() or exception()
|
| 94 |
+
# has consumed the exception
|
| 95 |
+
return
|
| 96 |
+
exc = self._exception
|
| 97 |
+
context = {
|
| 98 |
+
'message':
|
| 99 |
+
f'{self.__class__.__name__} exception was never retrieved',
|
| 100 |
+
'exception': exc,
|
| 101 |
+
'future': self,
|
| 102 |
+
}
|
| 103 |
+
if self._source_traceback:
|
| 104 |
+
context['source_traceback'] = self._source_traceback
|
| 105 |
+
self._loop.call_exception_handler(context)
|
| 106 |
+
|
| 107 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def _log_traceback(self):
|
| 111 |
+
return self.__log_traceback
|
| 112 |
+
|
| 113 |
+
@_log_traceback.setter
|
| 114 |
+
def _log_traceback(self, val):
|
| 115 |
+
if val:
|
| 116 |
+
raise ValueError('_log_traceback can only be set to False')
|
| 117 |
+
self.__log_traceback = False
|
| 118 |
+
|
| 119 |
+
def get_loop(self):
|
| 120 |
+
"""Return the event loop the Future is bound to."""
|
| 121 |
+
loop = self._loop
|
| 122 |
+
if loop is None:
|
| 123 |
+
raise RuntimeError("Future object is not initialized.")
|
| 124 |
+
return loop
|
| 125 |
+
|
| 126 |
+
def _make_cancelled_error(self):
|
| 127 |
+
"""Create the CancelledError to raise if the Future is cancelled.
|
| 128 |
+
|
| 129 |
+
This should only be called once when handling a cancellation since
|
| 130 |
+
it erases the saved context exception value.
|
| 131 |
+
"""
|
| 132 |
+
if self._cancelled_exc is not None:
|
| 133 |
+
exc = self._cancelled_exc
|
| 134 |
+
self._cancelled_exc = None
|
| 135 |
+
return exc
|
| 136 |
+
|
| 137 |
+
if self._cancel_message is None:
|
| 138 |
+
exc = exceptions.CancelledError()
|
| 139 |
+
else:
|
| 140 |
+
exc = exceptions.CancelledError(self._cancel_message)
|
| 141 |
+
exc.__context__ = self._cancelled_exc
|
| 142 |
+
# Remove the reference since we don't need this anymore.
|
| 143 |
+
self._cancelled_exc = None
|
| 144 |
+
return exc
|
| 145 |
+
|
| 146 |
+
def cancel(self, msg=None):
|
| 147 |
+
"""Cancel the future and schedule callbacks.
|
| 148 |
+
|
| 149 |
+
If the future is already done or cancelled, return False. Otherwise,
|
| 150 |
+
change the future's state to cancelled, schedule the callbacks and
|
| 151 |
+
return True.
|
| 152 |
+
"""
|
| 153 |
+
self.__log_traceback = False
|
| 154 |
+
if self._state != _PENDING:
|
| 155 |
+
return False
|
| 156 |
+
self._state = _CANCELLED
|
| 157 |
+
self._cancel_message = msg
|
| 158 |
+
self.__schedule_callbacks()
|
| 159 |
+
return True
|
| 160 |
+
|
| 161 |
+
def __schedule_callbacks(self):
|
| 162 |
+
"""Internal: Ask the event loop to call all callbacks.
|
| 163 |
+
|
| 164 |
+
The callbacks are scheduled to be called as soon as possible. Also
|
| 165 |
+
clears the callback list.
|
| 166 |
+
"""
|
| 167 |
+
callbacks = self._callbacks[:]
|
| 168 |
+
if not callbacks:
|
| 169 |
+
return
|
| 170 |
+
|
| 171 |
+
self._callbacks[:] = []
|
| 172 |
+
for callback, ctx in callbacks:
|
| 173 |
+
self._loop.call_soon(callback, self, context=ctx)
|
| 174 |
+
|
| 175 |
+
def cancelled(self):
|
| 176 |
+
"""Return True if the future was cancelled."""
|
| 177 |
+
return self._state == _CANCELLED
|
| 178 |
+
|
| 179 |
+
# Don't implement running(); see http://bugs.python.org/issue18699
|
| 180 |
+
|
| 181 |
+
def done(self):
|
| 182 |
+
"""Return True if the future is done.
|
| 183 |
+
|
| 184 |
+
Done means either that a result / exception are available, or that the
|
| 185 |
+
future was cancelled.
|
| 186 |
+
"""
|
| 187 |
+
return self._state != _PENDING
|
| 188 |
+
|
| 189 |
+
def result(self):
|
| 190 |
+
"""Return the result this future represents.
|
| 191 |
+
|
| 192 |
+
If the future has been cancelled, raises CancelledError. If the
|
| 193 |
+
future's result isn't yet available, raises InvalidStateError. If
|
| 194 |
+
the future is done and has an exception set, this exception is raised.
|
| 195 |
+
"""
|
| 196 |
+
if self._state == _CANCELLED:
|
| 197 |
+
exc = self._make_cancelled_error()
|
| 198 |
+
raise exc
|
| 199 |
+
if self._state != _FINISHED:
|
| 200 |
+
raise exceptions.InvalidStateError('Result is not ready.')
|
| 201 |
+
self.__log_traceback = False
|
| 202 |
+
if self._exception is not None:
|
| 203 |
+
raise self._exception.with_traceback(self._exception_tb)
|
| 204 |
+
return self._result
|
| 205 |
+
|
| 206 |
+
def exception(self):
|
| 207 |
+
"""Return the exception that was set on this future.
|
| 208 |
+
|
| 209 |
+
The exception (or None if no exception was set) is returned only if
|
| 210 |
+
the future is done. If the future has been cancelled, raises
|
| 211 |
+
CancelledError. If the future isn't done yet, raises
|
| 212 |
+
InvalidStateError.
|
| 213 |
+
"""
|
| 214 |
+
if self._state == _CANCELLED:
|
| 215 |
+
exc = self._make_cancelled_error()
|
| 216 |
+
raise exc
|
| 217 |
+
if self._state != _FINISHED:
|
| 218 |
+
raise exceptions.InvalidStateError('Exception is not set.')
|
| 219 |
+
self.__log_traceback = False
|
| 220 |
+
return self._exception
|
| 221 |
+
|
| 222 |
+
def add_done_callback(self, fn, *, context=None):
|
| 223 |
+
"""Add a callback to be run when the future becomes done.
|
| 224 |
+
|
| 225 |
+
The callback is called with a single argument - the future object. If
|
| 226 |
+
the future is already done when this is called, the callback is
|
| 227 |
+
scheduled with call_soon.
|
| 228 |
+
"""
|
| 229 |
+
if self._state != _PENDING:
|
| 230 |
+
self._loop.call_soon(fn, self, context=context)
|
| 231 |
+
else:
|
| 232 |
+
if context is None:
|
| 233 |
+
context = contextvars.copy_context()
|
| 234 |
+
self._callbacks.append((fn, context))
|
| 235 |
+
|
| 236 |
+
# New method not in PEP 3148.
|
| 237 |
+
|
| 238 |
+
def remove_done_callback(self, fn):
|
| 239 |
+
"""Remove all instances of a callback from the "call when done" list.
|
| 240 |
+
|
| 241 |
+
Returns the number of callbacks removed.
|
| 242 |
+
"""
|
| 243 |
+
filtered_callbacks = [(f, ctx)
|
| 244 |
+
for (f, ctx) in self._callbacks
|
| 245 |
+
if f != fn]
|
| 246 |
+
removed_count = len(self._callbacks) - len(filtered_callbacks)
|
| 247 |
+
if removed_count:
|
| 248 |
+
self._callbacks[:] = filtered_callbacks
|
| 249 |
+
return removed_count
|
| 250 |
+
|
| 251 |
+
# So-called internal methods (note: no set_running_or_notify_cancel()).
|
| 252 |
+
|
| 253 |
+
def set_result(self, result):
|
| 254 |
+
"""Mark the future done and set its result.
|
| 255 |
+
|
| 256 |
+
If the future is already done when this method is called, raises
|
| 257 |
+
InvalidStateError.
|
| 258 |
+
"""
|
| 259 |
+
if self._state != _PENDING:
|
| 260 |
+
raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
|
| 261 |
+
self._result = result
|
| 262 |
+
self._state = _FINISHED
|
| 263 |
+
self.__schedule_callbacks()
|
| 264 |
+
|
| 265 |
+
def set_exception(self, exception):
|
| 266 |
+
"""Mark the future done and set an exception.
|
| 267 |
+
|
| 268 |
+
If the future is already done when this method is called, raises
|
| 269 |
+
InvalidStateError.
|
| 270 |
+
"""
|
| 271 |
+
if self._state != _PENDING:
|
| 272 |
+
raise exceptions.InvalidStateError(f'{self._state}: {self!r}')
|
| 273 |
+
if isinstance(exception, type):
|
| 274 |
+
exception = exception()
|
| 275 |
+
if type(exception) is StopIteration:
|
| 276 |
+
raise TypeError("StopIteration interacts badly with generators "
|
| 277 |
+
"and cannot be raised into a Future")
|
| 278 |
+
self._exception = exception
|
| 279 |
+
self._exception_tb = exception.__traceback__
|
| 280 |
+
self._state = _FINISHED
|
| 281 |
+
self.__schedule_callbacks()
|
| 282 |
+
self.__log_traceback = True
|
| 283 |
+
|
| 284 |
+
def __await__(self):
|
| 285 |
+
if not self.done():
|
| 286 |
+
self._asyncio_future_blocking = True
|
| 287 |
+
yield self # This tells Task to wait for completion.
|
| 288 |
+
if not self.done():
|
| 289 |
+
raise RuntimeError("await wasn't used with future")
|
| 290 |
+
return self.result() # May raise too.
|
| 291 |
+
|
| 292 |
+
__iter__ = __await__ # make compatible with 'yield from'.
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
# Needed for testing purposes.
|
| 296 |
+
_PyFuture = Future
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def _get_loop(fut):
|
| 300 |
+
# Tries to call Future.get_loop() if it's available.
|
| 301 |
+
# Otherwise fallbacks to using the old '_loop' property.
|
| 302 |
+
try:
|
| 303 |
+
get_loop = fut.get_loop
|
| 304 |
+
except AttributeError:
|
| 305 |
+
pass
|
| 306 |
+
else:
|
| 307 |
+
return get_loop()
|
| 308 |
+
return fut._loop
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _set_result_unless_cancelled(fut, result):
|
| 312 |
+
"""Helper setting the result only if the future was not cancelled."""
|
| 313 |
+
if fut.cancelled():
|
| 314 |
+
return
|
| 315 |
+
fut.set_result(result)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def _convert_future_exc(exc):
|
| 319 |
+
exc_class = type(exc)
|
| 320 |
+
if exc_class is concurrent.futures.CancelledError:
|
| 321 |
+
return exceptions.CancelledError(*exc.args)
|
| 322 |
+
elif exc_class is concurrent.futures.TimeoutError:
|
| 323 |
+
return exceptions.TimeoutError(*exc.args)
|
| 324 |
+
elif exc_class is concurrent.futures.InvalidStateError:
|
| 325 |
+
return exceptions.InvalidStateError(*exc.args)
|
| 326 |
+
else:
|
| 327 |
+
return exc
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _set_concurrent_future_state(concurrent, source):
|
| 331 |
+
"""Copy state from a future to a concurrent.futures.Future."""
|
| 332 |
+
assert source.done()
|
| 333 |
+
if source.cancelled():
|
| 334 |
+
concurrent.cancel()
|
| 335 |
+
if not concurrent.set_running_or_notify_cancel():
|
| 336 |
+
return
|
| 337 |
+
exception = source.exception()
|
| 338 |
+
if exception is not None:
|
| 339 |
+
concurrent.set_exception(_convert_future_exc(exception))
|
| 340 |
+
else:
|
| 341 |
+
result = source.result()
|
| 342 |
+
concurrent.set_result(result)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def _copy_future_state(source, dest):
|
| 346 |
+
"""Internal helper to copy state from another Future.
|
| 347 |
+
|
| 348 |
+
The other Future may be a concurrent.futures.Future.
|
| 349 |
+
"""
|
| 350 |
+
assert source.done()
|
| 351 |
+
if dest.cancelled():
|
| 352 |
+
return
|
| 353 |
+
assert not dest.done()
|
| 354 |
+
if source.cancelled():
|
| 355 |
+
dest.cancel()
|
| 356 |
+
else:
|
| 357 |
+
exception = source.exception()
|
| 358 |
+
if exception is not None:
|
| 359 |
+
dest.set_exception(_convert_future_exc(exception))
|
| 360 |
+
else:
|
| 361 |
+
result = source.result()
|
| 362 |
+
dest.set_result(result)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def _chain_future(source, destination):
|
| 366 |
+
"""Chain two futures so that when one completes, so does the other.
|
| 367 |
+
|
| 368 |
+
The result (or exception) of source will be copied to destination.
|
| 369 |
+
If destination is cancelled, source gets cancelled too.
|
| 370 |
+
Compatible with both asyncio.Future and concurrent.futures.Future.
|
| 371 |
+
"""
|
| 372 |
+
if not isfuture(source) and not isinstance(source,
|
| 373 |
+
concurrent.futures.Future):
|
| 374 |
+
raise TypeError('A future is required for source argument')
|
| 375 |
+
if not isfuture(destination) and not isinstance(destination,
|
| 376 |
+
concurrent.futures.Future):
|
| 377 |
+
raise TypeError('A future is required for destination argument')
|
| 378 |
+
source_loop = _get_loop(source) if isfuture(source) else None
|
| 379 |
+
dest_loop = _get_loop(destination) if isfuture(destination) else None
|
| 380 |
+
|
| 381 |
+
def _set_state(future, other):
|
| 382 |
+
if isfuture(future):
|
| 383 |
+
_copy_future_state(other, future)
|
| 384 |
+
else:
|
| 385 |
+
_set_concurrent_future_state(future, other)
|
| 386 |
+
|
| 387 |
+
def _call_check_cancel(destination):
|
| 388 |
+
if destination.cancelled():
|
| 389 |
+
if source_loop is None or source_loop is dest_loop:
|
| 390 |
+
source.cancel()
|
| 391 |
+
else:
|
| 392 |
+
source_loop.call_soon_threadsafe(source.cancel)
|
| 393 |
+
|
| 394 |
+
def _call_set_state(source):
|
| 395 |
+
if (destination.cancelled() and
|
| 396 |
+
dest_loop is not None and dest_loop.is_closed()):
|
| 397 |
+
return
|
| 398 |
+
if dest_loop is None or dest_loop is source_loop:
|
| 399 |
+
_set_state(destination, source)
|
| 400 |
+
else:
|
| 401 |
+
if dest_loop.is_closed():
|
| 402 |
+
return
|
| 403 |
+
dest_loop.call_soon_threadsafe(_set_state, destination, source)
|
| 404 |
+
|
| 405 |
+
destination.add_done_callback(_call_check_cancel)
|
| 406 |
+
source.add_done_callback(_call_set_state)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def wrap_future(future, *, loop=None):
|
| 410 |
+
"""Wrap concurrent.futures.Future object."""
|
| 411 |
+
if isfuture(future):
|
| 412 |
+
return future
|
| 413 |
+
assert isinstance(future, concurrent.futures.Future), \
|
| 414 |
+
f'concurrent.futures.Future is expected, got {future!r}'
|
| 415 |
+
if loop is None:
|
| 416 |
+
loop = events._get_event_loop()
|
| 417 |
+
new_future = loop.create_future()
|
| 418 |
+
_chain_future(future, new_future)
|
| 419 |
+
return new_future
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
try:
|
| 423 |
+
import _asyncio
|
| 424 |
+
except ImportError:
|
| 425 |
+
pass
|
| 426 |
+
else:
|
| 427 |
+
# _CFuture is needed for tests.
|
| 428 |
+
Future = _CFuture = _asyncio.Future
|
micromamba_root/envs/pytorch_env/Lib/asyncio/locks.py
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ization primitives."""
|
| 2 |
+
|
| 3 |
+
__all__ = ('Lock', 'Event', 'Condition', 'Semaphore',
|
| 4 |
+
'BoundedSemaphore', 'Barrier')
|
| 5 |
+
|
| 6 |
+
import collections
|
| 7 |
+
import enum
|
| 8 |
+
|
| 9 |
+
from . import exceptions
|
| 10 |
+
from . import mixins
|
| 11 |
+
from . import tasks
|
| 12 |
+
|
| 13 |
+
class _ContextManagerMixin:
|
| 14 |
+
async def __aenter__(self):
|
| 15 |
+
await self.acquire()
|
| 16 |
+
# We have no use for the "as ..." clause in the with
|
| 17 |
+
# statement for locks.
|
| 18 |
+
return None
|
| 19 |
+
|
| 20 |
+
async def __aexit__(self, exc_type, exc, tb):
|
| 21 |
+
self.release()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Lock(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 25 |
+
"""Primitive lock objects.
|
| 26 |
+
|
| 27 |
+
A primitive lock is a synchronization primitive that is not owned
|
| 28 |
+
by a particular coroutine when locked. A primitive lock is in one
|
| 29 |
+
of two states, 'locked' or 'unlocked'.
|
| 30 |
+
|
| 31 |
+
It is created in the unlocked state. It has two basic methods,
|
| 32 |
+
acquire() and release(). When the state is unlocked, acquire()
|
| 33 |
+
changes the state to locked and returns immediately. When the
|
| 34 |
+
state is locked, acquire() blocks until a call to release() in
|
| 35 |
+
another coroutine changes it to unlocked, then the acquire() call
|
| 36 |
+
resets it to locked and returns. The release() method should only
|
| 37 |
+
be called in the locked state; it changes the state to unlocked
|
| 38 |
+
and returns immediately. If an attempt is made to release an
|
| 39 |
+
unlocked lock, a RuntimeError will be raised.
|
| 40 |
+
|
| 41 |
+
When more than one coroutine is blocked in acquire() waiting for
|
| 42 |
+
the state to turn to unlocked, only one coroutine proceeds when a
|
| 43 |
+
release() call resets the state to unlocked; first coroutine which
|
| 44 |
+
is blocked in acquire() is being processed.
|
| 45 |
+
|
| 46 |
+
acquire() is a coroutine and should be called with 'await'.
|
| 47 |
+
|
| 48 |
+
Locks also support the asynchronous context management protocol.
|
| 49 |
+
'async with lock' statement should be used.
|
| 50 |
+
|
| 51 |
+
Usage:
|
| 52 |
+
|
| 53 |
+
lock = Lock()
|
| 54 |
+
...
|
| 55 |
+
await lock.acquire()
|
| 56 |
+
try:
|
| 57 |
+
...
|
| 58 |
+
finally:
|
| 59 |
+
lock.release()
|
| 60 |
+
|
| 61 |
+
Context manager usage:
|
| 62 |
+
|
| 63 |
+
lock = Lock()
|
| 64 |
+
...
|
| 65 |
+
async with lock:
|
| 66 |
+
...
|
| 67 |
+
|
| 68 |
+
Lock objects can be tested for locking state:
|
| 69 |
+
|
| 70 |
+
if not lock.locked():
|
| 71 |
+
await lock.acquire()
|
| 72 |
+
else:
|
| 73 |
+
# lock is acquired
|
| 74 |
+
...
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
def __init__(self):
|
| 79 |
+
self._waiters = None
|
| 80 |
+
self._locked = False
|
| 81 |
+
|
| 82 |
+
def __repr__(self):
|
| 83 |
+
res = super().__repr__()
|
| 84 |
+
extra = 'locked' if self._locked else 'unlocked'
|
| 85 |
+
if self._waiters:
|
| 86 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 87 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 88 |
+
|
| 89 |
+
def locked(self):
|
| 90 |
+
"""Return True if lock is acquired."""
|
| 91 |
+
return self._locked
|
| 92 |
+
|
| 93 |
+
async def acquire(self):
|
| 94 |
+
"""Acquire a lock.
|
| 95 |
+
|
| 96 |
+
This method blocks until the lock is unlocked, then sets it to
|
| 97 |
+
locked and returns True.
|
| 98 |
+
"""
|
| 99 |
+
if (not self._locked and (self._waiters is None or
|
| 100 |
+
all(w.cancelled() for w in self._waiters))):
|
| 101 |
+
self._locked = True
|
| 102 |
+
return True
|
| 103 |
+
|
| 104 |
+
if self._waiters is None:
|
| 105 |
+
self._waiters = collections.deque()
|
| 106 |
+
fut = self._get_loop().create_future()
|
| 107 |
+
self._waiters.append(fut)
|
| 108 |
+
|
| 109 |
+
# Finally block should be called before the CancelledError
|
| 110 |
+
# handling as we don't want CancelledError to call
|
| 111 |
+
# _wake_up_first() and attempt to wake up itself.
|
| 112 |
+
try:
|
| 113 |
+
try:
|
| 114 |
+
await fut
|
| 115 |
+
finally:
|
| 116 |
+
self._waiters.remove(fut)
|
| 117 |
+
except exceptions.CancelledError:
|
| 118 |
+
if not self._locked:
|
| 119 |
+
self._wake_up_first()
|
| 120 |
+
raise
|
| 121 |
+
|
| 122 |
+
self._locked = True
|
| 123 |
+
return True
|
| 124 |
+
|
| 125 |
+
def release(self):
|
| 126 |
+
"""Release a lock.
|
| 127 |
+
|
| 128 |
+
When the lock is locked, reset it to unlocked, and return.
|
| 129 |
+
If any other coroutines are blocked waiting for the lock to become
|
| 130 |
+
unlocked, allow exactly one of them to proceed.
|
| 131 |
+
|
| 132 |
+
When invoked on an unlocked lock, a RuntimeError is raised.
|
| 133 |
+
|
| 134 |
+
There is no return value.
|
| 135 |
+
"""
|
| 136 |
+
if self._locked:
|
| 137 |
+
self._locked = False
|
| 138 |
+
self._wake_up_first()
|
| 139 |
+
else:
|
| 140 |
+
raise RuntimeError('Lock is not acquired.')
|
| 141 |
+
|
| 142 |
+
def _wake_up_first(self):
|
| 143 |
+
"""Wake up the first waiter if it isn't done."""
|
| 144 |
+
if not self._waiters:
|
| 145 |
+
return
|
| 146 |
+
try:
|
| 147 |
+
fut = next(iter(self._waiters))
|
| 148 |
+
except StopIteration:
|
| 149 |
+
return
|
| 150 |
+
|
| 151 |
+
# .done() necessarily means that a waiter will wake up later on and
|
| 152 |
+
# either take the lock, or, if it was cancelled and lock wasn't
|
| 153 |
+
# taken already, will hit this again and wake up a new waiter.
|
| 154 |
+
if not fut.done():
|
| 155 |
+
fut.set_result(True)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class Event(mixins._LoopBoundMixin):
|
| 159 |
+
"""Asynchronous equivalent to threading.Event.
|
| 160 |
+
|
| 161 |
+
Class implementing event objects. An event manages a flag that can be set
|
| 162 |
+
to true with the set() method and reset to false with the clear() method.
|
| 163 |
+
The wait() method blocks until the flag is true. The flag is initially
|
| 164 |
+
false.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(self):
|
| 168 |
+
self._waiters = collections.deque()
|
| 169 |
+
self._value = False
|
| 170 |
+
|
| 171 |
+
def __repr__(self):
|
| 172 |
+
res = super().__repr__()
|
| 173 |
+
extra = 'set' if self._value else 'unset'
|
| 174 |
+
if self._waiters:
|
| 175 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 176 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 177 |
+
|
| 178 |
+
def is_set(self):
|
| 179 |
+
"""Return True if and only if the internal flag is true."""
|
| 180 |
+
return self._value
|
| 181 |
+
|
| 182 |
+
def set(self):
|
| 183 |
+
"""Set the internal flag to true. All coroutines waiting for it to
|
| 184 |
+
become true are awakened. Coroutine that call wait() once the flag is
|
| 185 |
+
true will not block at all.
|
| 186 |
+
"""
|
| 187 |
+
if not self._value:
|
| 188 |
+
self._value = True
|
| 189 |
+
|
| 190 |
+
for fut in self._waiters:
|
| 191 |
+
if not fut.done():
|
| 192 |
+
fut.set_result(True)
|
| 193 |
+
|
| 194 |
+
def clear(self):
|
| 195 |
+
"""Reset the internal flag to false. Subsequently, coroutines calling
|
| 196 |
+
wait() will block until set() is called to set the internal flag
|
| 197 |
+
to true again."""
|
| 198 |
+
self._value = False
|
| 199 |
+
|
| 200 |
+
async def wait(self):
|
| 201 |
+
"""Block until the internal flag is true.
|
| 202 |
+
|
| 203 |
+
If the internal flag is true on entry, return True
|
| 204 |
+
immediately. Otherwise, block until another coroutine calls
|
| 205 |
+
set() to set the flag to true, then return True.
|
| 206 |
+
"""
|
| 207 |
+
if self._value:
|
| 208 |
+
return True
|
| 209 |
+
|
| 210 |
+
fut = self._get_loop().create_future()
|
| 211 |
+
self._waiters.append(fut)
|
| 212 |
+
try:
|
| 213 |
+
await fut
|
| 214 |
+
return True
|
| 215 |
+
finally:
|
| 216 |
+
self._waiters.remove(fut)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
class Condition(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 220 |
+
"""Asynchronous equivalent to threading.Condition.
|
| 221 |
+
|
| 222 |
+
This class implements condition variable objects. A condition variable
|
| 223 |
+
allows one or more coroutines to wait until they are notified by another
|
| 224 |
+
coroutine.
|
| 225 |
+
|
| 226 |
+
A new Lock object is created and used as the underlying lock.
|
| 227 |
+
"""
|
| 228 |
+
|
| 229 |
+
def __init__(self, lock=None):
|
| 230 |
+
if lock is None:
|
| 231 |
+
lock = Lock()
|
| 232 |
+
|
| 233 |
+
self._lock = lock
|
| 234 |
+
# Export the lock's locked(), acquire() and release() methods.
|
| 235 |
+
self.locked = lock.locked
|
| 236 |
+
self.acquire = lock.acquire
|
| 237 |
+
self.release = lock.release
|
| 238 |
+
|
| 239 |
+
self._waiters = collections.deque()
|
| 240 |
+
|
| 241 |
+
def __repr__(self):
|
| 242 |
+
res = super().__repr__()
|
| 243 |
+
extra = 'locked' if self.locked() else 'unlocked'
|
| 244 |
+
if self._waiters:
|
| 245 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 246 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 247 |
+
|
| 248 |
+
async def wait(self):
|
| 249 |
+
"""Wait until notified.
|
| 250 |
+
|
| 251 |
+
If the calling coroutine has not acquired the lock when this
|
| 252 |
+
method is called, a RuntimeError is raised.
|
| 253 |
+
|
| 254 |
+
This method releases the underlying lock, and then blocks
|
| 255 |
+
until it is awakened by a notify() or notify_all() call for
|
| 256 |
+
the same condition variable in another coroutine. Once
|
| 257 |
+
awakened, it re-acquires the lock and returns True.
|
| 258 |
+
"""
|
| 259 |
+
if not self.locked():
|
| 260 |
+
raise RuntimeError('cannot wait on un-acquired lock')
|
| 261 |
+
|
| 262 |
+
self.release()
|
| 263 |
+
try:
|
| 264 |
+
fut = self._get_loop().create_future()
|
| 265 |
+
self._waiters.append(fut)
|
| 266 |
+
try:
|
| 267 |
+
await fut
|
| 268 |
+
return True
|
| 269 |
+
finally:
|
| 270 |
+
self._waiters.remove(fut)
|
| 271 |
+
|
| 272 |
+
finally:
|
| 273 |
+
# Must reacquire lock even if wait is cancelled
|
| 274 |
+
cancelled = False
|
| 275 |
+
while True:
|
| 276 |
+
try:
|
| 277 |
+
await self.acquire()
|
| 278 |
+
break
|
| 279 |
+
except exceptions.CancelledError:
|
| 280 |
+
cancelled = True
|
| 281 |
+
|
| 282 |
+
if cancelled:
|
| 283 |
+
raise exceptions.CancelledError
|
| 284 |
+
|
| 285 |
+
async def wait_for(self, predicate):
|
| 286 |
+
"""Wait until a predicate becomes true.
|
| 287 |
+
|
| 288 |
+
The predicate should be a callable which result will be
|
| 289 |
+
interpreted as a boolean value. The final predicate value is
|
| 290 |
+
the return value.
|
| 291 |
+
"""
|
| 292 |
+
result = predicate()
|
| 293 |
+
while not result:
|
| 294 |
+
await self.wait()
|
| 295 |
+
result = predicate()
|
| 296 |
+
return result
|
| 297 |
+
|
| 298 |
+
def notify(self, n=1):
|
| 299 |
+
"""By default, wake up one coroutine waiting on this condition, if any.
|
| 300 |
+
If the calling coroutine has not acquired the lock when this method
|
| 301 |
+
is called, a RuntimeError is raised.
|
| 302 |
+
|
| 303 |
+
This method wakes up at most n of the coroutines waiting for the
|
| 304 |
+
condition variable; it is a no-op if no coroutines are waiting.
|
| 305 |
+
|
| 306 |
+
Note: an awakened coroutine does not actually return from its
|
| 307 |
+
wait() call until it can reacquire the lock. Since notify() does
|
| 308 |
+
not release the lock, its caller should.
|
| 309 |
+
"""
|
| 310 |
+
if not self.locked():
|
| 311 |
+
raise RuntimeError('cannot notify on un-acquired lock')
|
| 312 |
+
|
| 313 |
+
idx = 0
|
| 314 |
+
for fut in self._waiters:
|
| 315 |
+
if idx >= n:
|
| 316 |
+
break
|
| 317 |
+
|
| 318 |
+
if not fut.done():
|
| 319 |
+
idx += 1
|
| 320 |
+
fut.set_result(False)
|
| 321 |
+
|
| 322 |
+
def notify_all(self):
|
| 323 |
+
"""Wake up all threads waiting on this condition. This method acts
|
| 324 |
+
like notify(), but wakes up all waiting threads instead of one. If the
|
| 325 |
+
calling thread has not acquired the lock when this method is called,
|
| 326 |
+
a RuntimeError is raised.
|
| 327 |
+
"""
|
| 328 |
+
self.notify(len(self._waiters))
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class Semaphore(_ContextManagerMixin, mixins._LoopBoundMixin):
|
| 332 |
+
"""A Semaphore implementation.
|
| 333 |
+
|
| 334 |
+
A semaphore manages an internal counter which is decremented by each
|
| 335 |
+
acquire() call and incremented by each release() call. The counter
|
| 336 |
+
can never go below zero; when acquire() finds that it is zero, it blocks,
|
| 337 |
+
waiting until some other thread calls release().
|
| 338 |
+
|
| 339 |
+
Semaphores also support the context management protocol.
|
| 340 |
+
|
| 341 |
+
The optional argument gives the initial value for the internal
|
| 342 |
+
counter; it defaults to 1. If the value given is less than 0,
|
| 343 |
+
ValueError is raised.
|
| 344 |
+
"""
|
| 345 |
+
|
| 346 |
+
def __init__(self, value=1):
|
| 347 |
+
if value < 0:
|
| 348 |
+
raise ValueError("Semaphore initial value must be >= 0")
|
| 349 |
+
self._waiters = None
|
| 350 |
+
self._value = value
|
| 351 |
+
|
| 352 |
+
def __repr__(self):
|
| 353 |
+
res = super().__repr__()
|
| 354 |
+
extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
|
| 355 |
+
if self._waiters:
|
| 356 |
+
extra = f'{extra}, waiters:{len(self._waiters)}'
|
| 357 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 358 |
+
|
| 359 |
+
def locked(self):
|
| 360 |
+
"""Returns True if semaphore cannot be acquired immediately."""
|
| 361 |
+
return self._value == 0 or (
|
| 362 |
+
any(not w.cancelled() for w in (self._waiters or ())))
|
| 363 |
+
|
| 364 |
+
async def acquire(self):
|
| 365 |
+
"""Acquire a semaphore.
|
| 366 |
+
|
| 367 |
+
If the internal counter is larger than zero on entry,
|
| 368 |
+
decrement it by one and return True immediately. If it is
|
| 369 |
+
zero on entry, block, waiting until some other coroutine has
|
| 370 |
+
called release() to make it larger than 0, and then return
|
| 371 |
+
True.
|
| 372 |
+
"""
|
| 373 |
+
if not self.locked():
|
| 374 |
+
self._value -= 1
|
| 375 |
+
return True
|
| 376 |
+
|
| 377 |
+
if self._waiters is None:
|
| 378 |
+
self._waiters = collections.deque()
|
| 379 |
+
fut = self._get_loop().create_future()
|
| 380 |
+
self._waiters.append(fut)
|
| 381 |
+
|
| 382 |
+
# Finally block should be called before the CancelledError
|
| 383 |
+
# handling as we don't want CancelledError to call
|
| 384 |
+
# _wake_up_first() and attempt to wake up itself.
|
| 385 |
+
try:
|
| 386 |
+
try:
|
| 387 |
+
await fut
|
| 388 |
+
finally:
|
| 389 |
+
self._waiters.remove(fut)
|
| 390 |
+
except exceptions.CancelledError:
|
| 391 |
+
if not fut.cancelled():
|
| 392 |
+
self._value += 1
|
| 393 |
+
self._wake_up_next()
|
| 394 |
+
raise
|
| 395 |
+
|
| 396 |
+
if self._value > 0:
|
| 397 |
+
self._wake_up_next()
|
| 398 |
+
return True
|
| 399 |
+
|
| 400 |
+
def release(self):
|
| 401 |
+
"""Release a semaphore, incrementing the internal counter by one.
|
| 402 |
+
|
| 403 |
+
When it was zero on entry and another coroutine is waiting for it to
|
| 404 |
+
become larger than zero again, wake up that coroutine.
|
| 405 |
+
"""
|
| 406 |
+
self._value += 1
|
| 407 |
+
self._wake_up_next()
|
| 408 |
+
|
| 409 |
+
def _wake_up_next(self):
|
| 410 |
+
"""Wake up the first waiter that isn't done."""
|
| 411 |
+
if not self._waiters:
|
| 412 |
+
return
|
| 413 |
+
|
| 414 |
+
for fut in self._waiters:
|
| 415 |
+
if not fut.done():
|
| 416 |
+
self._value -= 1
|
| 417 |
+
fut.set_result(True)
|
| 418 |
+
return
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class BoundedSemaphore(Semaphore):
|
| 422 |
+
"""A bounded semaphore implementation.
|
| 423 |
+
|
| 424 |
+
This raises ValueError in release() if it would increase the value
|
| 425 |
+
above the initial value.
|
| 426 |
+
"""
|
| 427 |
+
|
| 428 |
+
def __init__(self, value=1):
|
| 429 |
+
self._bound_value = value
|
| 430 |
+
super().__init__(value)
|
| 431 |
+
|
| 432 |
+
def release(self):
|
| 433 |
+
if self._value >= self._bound_value:
|
| 434 |
+
raise ValueError('BoundedSemaphore released too many times')
|
| 435 |
+
super().release()
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
class _BarrierState(enum.Enum):
|
| 440 |
+
FILLING = 'filling'
|
| 441 |
+
DRAINING = 'draining'
|
| 442 |
+
RESETTING = 'resetting'
|
| 443 |
+
BROKEN = 'broken'
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
class Barrier(mixins._LoopBoundMixin):
|
| 447 |
+
"""Asyncio equivalent to threading.Barrier
|
| 448 |
+
|
| 449 |
+
Implements a Barrier primitive.
|
| 450 |
+
Useful for synchronizing a fixed number of tasks at known synchronization
|
| 451 |
+
points. Tasks block on 'wait()' and are simultaneously awoken once they
|
| 452 |
+
have all made their call.
|
| 453 |
+
"""
|
| 454 |
+
|
| 455 |
+
def __init__(self, parties):
|
| 456 |
+
"""Create a barrier, initialised to 'parties' tasks."""
|
| 457 |
+
if parties < 1:
|
| 458 |
+
raise ValueError('parties must be > 0')
|
| 459 |
+
|
| 460 |
+
self._cond = Condition() # notify all tasks when state changes
|
| 461 |
+
|
| 462 |
+
self._parties = parties
|
| 463 |
+
self._state = _BarrierState.FILLING
|
| 464 |
+
self._count = 0 # count tasks in Barrier
|
| 465 |
+
|
| 466 |
+
def __repr__(self):
|
| 467 |
+
res = super().__repr__()
|
| 468 |
+
extra = f'{self._state.value}'
|
| 469 |
+
if not self.broken:
|
| 470 |
+
extra += f', waiters:{self.n_waiting}/{self.parties}'
|
| 471 |
+
return f'<{res[1:-1]} [{extra}]>'
|
| 472 |
+
|
| 473 |
+
async def __aenter__(self):
|
| 474 |
+
# wait for the barrier reaches the parties number
|
| 475 |
+
# when start draining release and return index of waited task
|
| 476 |
+
return await self.wait()
|
| 477 |
+
|
| 478 |
+
async def __aexit__(self, *args):
|
| 479 |
+
pass
|
| 480 |
+
|
| 481 |
+
async def wait(self):
|
| 482 |
+
"""Wait for the barrier.
|
| 483 |
+
|
| 484 |
+
When the specified number of tasks have started waiting, they are all
|
| 485 |
+
simultaneously awoken.
|
| 486 |
+
Returns an unique and individual index number from 0 to 'parties-1'.
|
| 487 |
+
"""
|
| 488 |
+
async with self._cond:
|
| 489 |
+
await self._block() # Block while the barrier drains or resets.
|
| 490 |
+
try:
|
| 491 |
+
index = self._count
|
| 492 |
+
self._count += 1
|
| 493 |
+
if index + 1 == self._parties:
|
| 494 |
+
# We release the barrier
|
| 495 |
+
await self._release()
|
| 496 |
+
else:
|
| 497 |
+
await self._wait()
|
| 498 |
+
return index
|
| 499 |
+
finally:
|
| 500 |
+
self._count -= 1
|
| 501 |
+
# Wake up any tasks waiting for barrier to drain.
|
| 502 |
+
self._exit()
|
| 503 |
+
|
| 504 |
+
async def _block(self):
|
| 505 |
+
# Block until the barrier is ready for us,
|
| 506 |
+
# or raise an exception if it is broken.
|
| 507 |
+
#
|
| 508 |
+
# It is draining or resetting, wait until done
|
| 509 |
+
# unless a CancelledError occurs
|
| 510 |
+
await self._cond.wait_for(
|
| 511 |
+
lambda: self._state not in (
|
| 512 |
+
_BarrierState.DRAINING, _BarrierState.RESETTING
|
| 513 |
+
)
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
# see if the barrier is in a broken state
|
| 517 |
+
if self._state is _BarrierState.BROKEN:
|
| 518 |
+
raise exceptions.BrokenBarrierError("Barrier aborted")
|
| 519 |
+
|
| 520 |
+
async def _release(self):
|
| 521 |
+
# Release the tasks waiting in the barrier.
|
| 522 |
+
|
| 523 |
+
# Enter draining state.
|
| 524 |
+
# Next waiting tasks will be blocked until the end of draining.
|
| 525 |
+
self._state = _BarrierState.DRAINING
|
| 526 |
+
self._cond.notify_all()
|
| 527 |
+
|
| 528 |
+
async def _wait(self):
|
| 529 |
+
# Wait in the barrier until we are released. Raise an exception
|
| 530 |
+
# if the barrier is reset or broken.
|
| 531 |
+
|
| 532 |
+
# wait for end of filling
|
| 533 |
+
# unless a CancelledError occurs
|
| 534 |
+
await self._cond.wait_for(lambda: self._state is not _BarrierState.FILLING)
|
| 535 |
+
|
| 536 |
+
if self._state in (_BarrierState.BROKEN, _BarrierState.RESETTING):
|
| 537 |
+
raise exceptions.BrokenBarrierError("Abort or reset of barrier")
|
| 538 |
+
|
| 539 |
+
def _exit(self):
|
| 540 |
+
# If we are the last tasks to exit the barrier, signal any tasks
|
| 541 |
+
# waiting for the barrier to drain.
|
| 542 |
+
if self._count == 0:
|
| 543 |
+
if self._state in (_BarrierState.RESETTING, _BarrierState.DRAINING):
|
| 544 |
+
self._state = _BarrierState.FILLING
|
| 545 |
+
self._cond.notify_all()
|
| 546 |
+
|
| 547 |
+
async def reset(self):
|
| 548 |
+
"""Reset the barrier to the initial state.
|
| 549 |
+
|
| 550 |
+
Any tasks currently waiting will get the BrokenBarrier exception
|
| 551 |
+
raised.
|
| 552 |
+
"""
|
| 553 |
+
async with self._cond:
|
| 554 |
+
if self._count > 0:
|
| 555 |
+
if self._state is not _BarrierState.RESETTING:
|
| 556 |
+
#reset the barrier, waking up tasks
|
| 557 |
+
self._state = _BarrierState.RESETTING
|
| 558 |
+
else:
|
| 559 |
+
self._state = _BarrierState.FILLING
|
| 560 |
+
self._cond.notify_all()
|
| 561 |
+
|
| 562 |
+
async def abort(self):
|
| 563 |
+
"""Place the barrier into a 'broken' state.
|
| 564 |
+
|
| 565 |
+
Useful in case of error. Any currently waiting tasks and tasks
|
| 566 |
+
attempting to 'wait()' will have BrokenBarrierError raised.
|
| 567 |
+
"""
|
| 568 |
+
async with self._cond:
|
| 569 |
+
self._state = _BarrierState.BROKEN
|
| 570 |
+
self._cond.notify_all()
|
| 571 |
+
|
| 572 |
+
@property
|
| 573 |
+
def parties(self):
|
| 574 |
+
"""Return the number of tasks required to trip the barrier."""
|
| 575 |
+
return self._parties
|
| 576 |
+
|
| 577 |
+
@property
|
| 578 |
+
def n_waiting(self):
|
| 579 |
+
"""Return the number of tasks currently waiting at the barrier."""
|
| 580 |
+
if self._state is _BarrierState.FILLING:
|
| 581 |
+
return self._count
|
| 582 |
+
return 0
|
| 583 |
+
|
| 584 |
+
@property
|
| 585 |
+
def broken(self):
|
| 586 |
+
"""Return True if the barrier is in a broken state."""
|
| 587 |
+
return self._state is _BarrierState.BROKEN
|
micromamba_root/envs/pytorch_env/Lib/asyncio/log.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Logging configuration."""
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
# Name the logger after the package.
|
| 7 |
+
logger = logging.getLogger(__package__)
|
micromamba_root/envs/pytorch_env/Lib/asyncio/mixins.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event loop mixins."""
|
| 2 |
+
|
| 3 |
+
import threading
|
| 4 |
+
from . import events
|
| 5 |
+
|
| 6 |
+
_global_lock = threading.Lock()
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class _LoopBoundMixin:
|
| 10 |
+
_loop = None
|
| 11 |
+
|
| 12 |
+
def _get_loop(self):
|
| 13 |
+
loop = events._get_running_loop()
|
| 14 |
+
|
| 15 |
+
if self._loop is None:
|
| 16 |
+
with _global_lock:
|
| 17 |
+
if self._loop is None:
|
| 18 |
+
self._loop = loop
|
| 19 |
+
if loop is not self._loop:
|
| 20 |
+
raise RuntimeError(f'{self!r} is bound to a different event loop')
|
| 21 |
+
return loop
|
micromamba_root/envs/pytorch_env/Lib/asyncio/proactor_events.py
ADDED
|
@@ -0,0 +1,894 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event loop using a proactor and related classes.
|
| 2 |
+
|
| 3 |
+
A proactor is a "notify-on-completion" multiplexer. Currently a
|
| 4 |
+
proactor is only implemented on Windows with IOCP.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
__all__ = 'BaseProactorEventLoop',
|
| 8 |
+
|
| 9 |
+
import io
|
| 10 |
+
import os
|
| 11 |
+
import socket
|
| 12 |
+
import warnings
|
| 13 |
+
import signal
|
| 14 |
+
import threading
|
| 15 |
+
import collections
|
| 16 |
+
|
| 17 |
+
from . import base_events
|
| 18 |
+
from . import constants
|
| 19 |
+
from . import futures
|
| 20 |
+
from . import exceptions
|
| 21 |
+
from . import protocols
|
| 22 |
+
from . import sslproto
|
| 23 |
+
from . import transports
|
| 24 |
+
from . import trsock
|
| 25 |
+
from .log import logger
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _set_socket_extra(transport, sock):
|
| 29 |
+
transport._extra['socket'] = trsock.TransportSocket(sock)
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
transport._extra['sockname'] = sock.getsockname()
|
| 33 |
+
except socket.error:
|
| 34 |
+
if transport._loop.get_debug():
|
| 35 |
+
logger.warning(
|
| 36 |
+
"getsockname() failed on %r", sock, exc_info=True)
|
| 37 |
+
|
| 38 |
+
if 'peername' not in transport._extra:
|
| 39 |
+
try:
|
| 40 |
+
transport._extra['peername'] = sock.getpeername()
|
| 41 |
+
except socket.error:
|
| 42 |
+
# UDP sockets may not have a peer name
|
| 43 |
+
transport._extra['peername'] = None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class _ProactorBasePipeTransport(transports._FlowControlMixin,
|
| 47 |
+
transports.BaseTransport):
|
| 48 |
+
"""Base class for pipe and socket transports."""
|
| 49 |
+
|
| 50 |
+
def __init__(self, loop, sock, protocol, waiter=None,
|
| 51 |
+
extra=None, server=None):
|
| 52 |
+
super().__init__(extra, loop)
|
| 53 |
+
self._set_extra(sock)
|
| 54 |
+
self._sock = sock
|
| 55 |
+
self.set_protocol(protocol)
|
| 56 |
+
self._server = server
|
| 57 |
+
self._buffer = None # None or bytearray.
|
| 58 |
+
self._read_fut = None
|
| 59 |
+
self._write_fut = None
|
| 60 |
+
self._pending_write = 0
|
| 61 |
+
self._conn_lost = 0
|
| 62 |
+
self._closing = False # Set when close() called.
|
| 63 |
+
self._called_connection_lost = False
|
| 64 |
+
self._eof_written = False
|
| 65 |
+
if self._server is not None:
|
| 66 |
+
self._server._attach()
|
| 67 |
+
self._loop.call_soon(self._protocol.connection_made, self)
|
| 68 |
+
if waiter is not None:
|
| 69 |
+
# only wake up the waiter when connection_made() has been called
|
| 70 |
+
self._loop.call_soon(futures._set_result_unless_cancelled,
|
| 71 |
+
waiter, None)
|
| 72 |
+
|
| 73 |
+
def __repr__(self):
|
| 74 |
+
info = [self.__class__.__name__]
|
| 75 |
+
if self._sock is None:
|
| 76 |
+
info.append('closed')
|
| 77 |
+
elif self._closing:
|
| 78 |
+
info.append('closing')
|
| 79 |
+
if self._sock is not None:
|
| 80 |
+
info.append(f'fd={self._sock.fileno()}')
|
| 81 |
+
if self._read_fut is not None:
|
| 82 |
+
info.append(f'read={self._read_fut!r}')
|
| 83 |
+
if self._write_fut is not None:
|
| 84 |
+
info.append(f'write={self._write_fut!r}')
|
| 85 |
+
if self._buffer:
|
| 86 |
+
info.append(f'write_bufsize={len(self._buffer)}')
|
| 87 |
+
if self._eof_written:
|
| 88 |
+
info.append('EOF written')
|
| 89 |
+
return '<{}>'.format(' '.join(info))
|
| 90 |
+
|
| 91 |
+
def _set_extra(self, sock):
|
| 92 |
+
self._extra['pipe'] = sock
|
| 93 |
+
|
| 94 |
+
def set_protocol(self, protocol):
|
| 95 |
+
self._protocol = protocol
|
| 96 |
+
|
| 97 |
+
def get_protocol(self):
|
| 98 |
+
return self._protocol
|
| 99 |
+
|
| 100 |
+
def is_closing(self):
|
| 101 |
+
return self._closing
|
| 102 |
+
|
| 103 |
+
def close(self):
|
| 104 |
+
if self._closing:
|
| 105 |
+
return
|
| 106 |
+
self._closing = True
|
| 107 |
+
self._conn_lost += 1
|
| 108 |
+
if not self._buffer and self._write_fut is None:
|
| 109 |
+
self._loop.call_soon(self._call_connection_lost, None)
|
| 110 |
+
if self._read_fut is not None:
|
| 111 |
+
self._read_fut.cancel()
|
| 112 |
+
self._read_fut = None
|
| 113 |
+
|
| 114 |
+
def __del__(self, _warn=warnings.warn):
|
| 115 |
+
if self._sock is not None:
|
| 116 |
+
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
|
| 117 |
+
self._sock.close()
|
| 118 |
+
|
| 119 |
+
def _fatal_error(self, exc, message='Fatal error on pipe transport'):
|
| 120 |
+
try:
|
| 121 |
+
if isinstance(exc, OSError):
|
| 122 |
+
if self._loop.get_debug():
|
| 123 |
+
logger.debug("%r: %s", self, message, exc_info=True)
|
| 124 |
+
else:
|
| 125 |
+
self._loop.call_exception_handler({
|
| 126 |
+
'message': message,
|
| 127 |
+
'exception': exc,
|
| 128 |
+
'transport': self,
|
| 129 |
+
'protocol': self._protocol,
|
| 130 |
+
})
|
| 131 |
+
finally:
|
| 132 |
+
self._force_close(exc)
|
| 133 |
+
|
| 134 |
+
def _force_close(self, exc):
|
| 135 |
+
if self._empty_waiter is not None and not self._empty_waiter.done():
|
| 136 |
+
if exc is None:
|
| 137 |
+
self._empty_waiter.set_result(None)
|
| 138 |
+
else:
|
| 139 |
+
self._empty_waiter.set_exception(exc)
|
| 140 |
+
if self._closing and self._called_connection_lost:
|
| 141 |
+
return
|
| 142 |
+
self._closing = True
|
| 143 |
+
self._conn_lost += 1
|
| 144 |
+
if self._write_fut:
|
| 145 |
+
self._write_fut.cancel()
|
| 146 |
+
self._write_fut = None
|
| 147 |
+
if self._read_fut:
|
| 148 |
+
self._read_fut.cancel()
|
| 149 |
+
self._read_fut = None
|
| 150 |
+
self._pending_write = 0
|
| 151 |
+
self._buffer = None
|
| 152 |
+
self._loop.call_soon(self._call_connection_lost, exc)
|
| 153 |
+
|
| 154 |
+
def _call_connection_lost(self, exc):
|
| 155 |
+
if self._called_connection_lost:
|
| 156 |
+
return
|
| 157 |
+
try:
|
| 158 |
+
self._protocol.connection_lost(exc)
|
| 159 |
+
finally:
|
| 160 |
+
# XXX If there is a pending overlapped read on the other
|
| 161 |
+
# end then it may fail with ERROR_NETNAME_DELETED if we
|
| 162 |
+
# just close our end. First calling shutdown() seems to
|
| 163 |
+
# cure it, but maybe using DisconnectEx() would be better.
|
| 164 |
+
if hasattr(self._sock, 'shutdown') and self._sock.fileno() != -1:
|
| 165 |
+
self._sock.shutdown(socket.SHUT_RDWR)
|
| 166 |
+
self._sock.close()
|
| 167 |
+
self._sock = None
|
| 168 |
+
server = self._server
|
| 169 |
+
if server is not None:
|
| 170 |
+
server._detach()
|
| 171 |
+
self._server = None
|
| 172 |
+
self._called_connection_lost = True
|
| 173 |
+
|
| 174 |
+
def get_write_buffer_size(self):
|
| 175 |
+
size = self._pending_write
|
| 176 |
+
if self._buffer is not None:
|
| 177 |
+
size += len(self._buffer)
|
| 178 |
+
return size
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class _ProactorReadPipeTransport(_ProactorBasePipeTransport,
|
| 182 |
+
transports.ReadTransport):
|
| 183 |
+
"""Transport for read pipes."""
|
| 184 |
+
|
| 185 |
+
def __init__(self, loop, sock, protocol, waiter=None,
|
| 186 |
+
extra=None, server=None, buffer_size=65536):
|
| 187 |
+
self._pending_data_length = -1
|
| 188 |
+
self._paused = True
|
| 189 |
+
super().__init__(loop, sock, protocol, waiter, extra, server)
|
| 190 |
+
|
| 191 |
+
self._data = bytearray(buffer_size)
|
| 192 |
+
self._loop.call_soon(self._loop_reading)
|
| 193 |
+
self._paused = False
|
| 194 |
+
|
| 195 |
+
def is_reading(self):
|
| 196 |
+
return not self._paused and not self._closing
|
| 197 |
+
|
| 198 |
+
def pause_reading(self):
|
| 199 |
+
if self._closing or self._paused:
|
| 200 |
+
return
|
| 201 |
+
self._paused = True
|
| 202 |
+
|
| 203 |
+
# bpo-33694: Don't cancel self._read_fut because cancelling an
|
| 204 |
+
# overlapped WSASend() loss silently data with the current proactor
|
| 205 |
+
# implementation.
|
| 206 |
+
#
|
| 207 |
+
# If CancelIoEx() fails with ERROR_NOT_FOUND, it means that WSASend()
|
| 208 |
+
# completed (even if HasOverlappedIoCompleted() returns 0), but
|
| 209 |
+
# Overlapped.cancel() currently silently ignores the ERROR_NOT_FOUND
|
| 210 |
+
# error. Once the overlapped is ignored, the IOCP loop will ignores the
|
| 211 |
+
# completion I/O event and so not read the result of the overlapped
|
| 212 |
+
# WSARecv().
|
| 213 |
+
|
| 214 |
+
if self._loop.get_debug():
|
| 215 |
+
logger.debug("%r pauses reading", self)
|
| 216 |
+
|
| 217 |
+
def resume_reading(self):
|
| 218 |
+
if self._closing or not self._paused:
|
| 219 |
+
return
|
| 220 |
+
|
| 221 |
+
self._paused = False
|
| 222 |
+
if self._read_fut is None:
|
| 223 |
+
self._loop.call_soon(self._loop_reading, None)
|
| 224 |
+
|
| 225 |
+
length = self._pending_data_length
|
| 226 |
+
self._pending_data_length = -1
|
| 227 |
+
if length > -1:
|
| 228 |
+
# Call the protocol method after calling _loop_reading(),
|
| 229 |
+
# since the protocol can decide to pause reading again.
|
| 230 |
+
self._loop.call_soon(self._data_received, self._data[:length], length)
|
| 231 |
+
|
| 232 |
+
if self._loop.get_debug():
|
| 233 |
+
logger.debug("%r resumes reading", self)
|
| 234 |
+
|
| 235 |
+
def _eof_received(self):
|
| 236 |
+
if self._loop.get_debug():
|
| 237 |
+
logger.debug("%r received EOF", self)
|
| 238 |
+
|
| 239 |
+
try:
|
| 240 |
+
keep_open = self._protocol.eof_received()
|
| 241 |
+
except (SystemExit, KeyboardInterrupt):
|
| 242 |
+
raise
|
| 243 |
+
except BaseException as exc:
|
| 244 |
+
self._fatal_error(
|
| 245 |
+
exc, 'Fatal error: protocol.eof_received() call failed.')
|
| 246 |
+
return
|
| 247 |
+
|
| 248 |
+
if not keep_open:
|
| 249 |
+
self.close()
|
| 250 |
+
|
| 251 |
+
def _data_received(self, data, length):
|
| 252 |
+
if self._paused:
|
| 253 |
+
# Don't call any protocol method while reading is paused.
|
| 254 |
+
# The protocol will be called on resume_reading().
|
| 255 |
+
assert self._pending_data_length == -1
|
| 256 |
+
self._pending_data_length = length
|
| 257 |
+
return
|
| 258 |
+
|
| 259 |
+
if length == 0:
|
| 260 |
+
self._eof_received()
|
| 261 |
+
return
|
| 262 |
+
|
| 263 |
+
if isinstance(self._protocol, protocols.BufferedProtocol):
|
| 264 |
+
try:
|
| 265 |
+
protocols._feed_data_to_buffered_proto(self._protocol, data)
|
| 266 |
+
except (SystemExit, KeyboardInterrupt):
|
| 267 |
+
raise
|
| 268 |
+
except BaseException as exc:
|
| 269 |
+
self._fatal_error(exc,
|
| 270 |
+
'Fatal error: protocol.buffer_updated() '
|
| 271 |
+
'call failed.')
|
| 272 |
+
return
|
| 273 |
+
else:
|
| 274 |
+
self._protocol.data_received(data)
|
| 275 |
+
|
| 276 |
+
def _loop_reading(self, fut=None):
|
| 277 |
+
length = -1
|
| 278 |
+
data = None
|
| 279 |
+
try:
|
| 280 |
+
if fut is not None:
|
| 281 |
+
assert self._read_fut is fut or (self._read_fut is None and
|
| 282 |
+
self._closing)
|
| 283 |
+
self._read_fut = None
|
| 284 |
+
if fut.done():
|
| 285 |
+
# deliver data later in "finally" clause
|
| 286 |
+
length = fut.result()
|
| 287 |
+
if length == 0:
|
| 288 |
+
# we got end-of-file so no need to reschedule a new read
|
| 289 |
+
return
|
| 290 |
+
|
| 291 |
+
data = self._data[:length]
|
| 292 |
+
else:
|
| 293 |
+
# the future will be replaced by next proactor.recv call
|
| 294 |
+
fut.cancel()
|
| 295 |
+
|
| 296 |
+
if self._closing:
|
| 297 |
+
# since close() has been called we ignore any read data
|
| 298 |
+
return
|
| 299 |
+
|
| 300 |
+
# bpo-33694: buffer_updated() has currently no fast path because of
|
| 301 |
+
# a data loss issue caused by overlapped WSASend() cancellation.
|
| 302 |
+
|
| 303 |
+
if not self._paused:
|
| 304 |
+
# reschedule a new read
|
| 305 |
+
self._read_fut = self._loop._proactor.recv_into(self._sock, self._data)
|
| 306 |
+
except ConnectionAbortedError as exc:
|
| 307 |
+
if not self._closing:
|
| 308 |
+
self._fatal_error(exc, 'Fatal read error on pipe transport')
|
| 309 |
+
elif self._loop.get_debug():
|
| 310 |
+
logger.debug("Read error on pipe transport while closing",
|
| 311 |
+
exc_info=True)
|
| 312 |
+
except ConnectionResetError as exc:
|
| 313 |
+
self._force_close(exc)
|
| 314 |
+
except OSError as exc:
|
| 315 |
+
self._fatal_error(exc, 'Fatal read error on pipe transport')
|
| 316 |
+
except exceptions.CancelledError:
|
| 317 |
+
if not self._closing:
|
| 318 |
+
raise
|
| 319 |
+
else:
|
| 320 |
+
if not self._paused:
|
| 321 |
+
self._read_fut.add_done_callback(self._loop_reading)
|
| 322 |
+
finally:
|
| 323 |
+
if length > -1:
|
| 324 |
+
self._data_received(data, length)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport,
|
| 328 |
+
transports.WriteTransport):
|
| 329 |
+
"""Transport for write pipes."""
|
| 330 |
+
|
| 331 |
+
_start_tls_compatible = True
|
| 332 |
+
|
| 333 |
+
def __init__(self, *args, **kw):
|
| 334 |
+
super().__init__(*args, **kw)
|
| 335 |
+
self._empty_waiter = None
|
| 336 |
+
|
| 337 |
+
def write(self, data):
|
| 338 |
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
| 339 |
+
raise TypeError(
|
| 340 |
+
f"data argument must be a bytes-like object, "
|
| 341 |
+
f"not {type(data).__name__}")
|
| 342 |
+
if self._eof_written:
|
| 343 |
+
raise RuntimeError('write_eof() already called')
|
| 344 |
+
if self._empty_waiter is not None:
|
| 345 |
+
raise RuntimeError('unable to write; sendfile is in progress')
|
| 346 |
+
|
| 347 |
+
if not data:
|
| 348 |
+
return
|
| 349 |
+
|
| 350 |
+
if self._conn_lost:
|
| 351 |
+
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
|
| 352 |
+
logger.warning('socket.send() raised exception.')
|
| 353 |
+
self._conn_lost += 1
|
| 354 |
+
return
|
| 355 |
+
|
| 356 |
+
# Observable states:
|
| 357 |
+
# 1. IDLE: _write_fut and _buffer both None
|
| 358 |
+
# 2. WRITING: _write_fut set; _buffer None
|
| 359 |
+
# 3. BACKED UP: _write_fut set; _buffer a bytearray
|
| 360 |
+
# We always copy the data, so the caller can't modify it
|
| 361 |
+
# while we're still waiting for the I/O to happen.
|
| 362 |
+
if self._write_fut is None: # IDLE -> WRITING
|
| 363 |
+
assert self._buffer is None
|
| 364 |
+
# Pass a copy, except if it's already immutable.
|
| 365 |
+
self._loop_writing(data=bytes(data))
|
| 366 |
+
elif not self._buffer: # WRITING -> BACKED UP
|
| 367 |
+
# Make a mutable copy which we can extend.
|
| 368 |
+
self._buffer = bytearray(data)
|
| 369 |
+
self._maybe_pause_protocol()
|
| 370 |
+
else: # BACKED UP
|
| 371 |
+
# Append to buffer (also copies).
|
| 372 |
+
self._buffer.extend(data)
|
| 373 |
+
self._maybe_pause_protocol()
|
| 374 |
+
|
| 375 |
+
def _loop_writing(self, f=None, data=None):
|
| 376 |
+
try:
|
| 377 |
+
if f is not None and self._write_fut is None and self._closing:
|
| 378 |
+
# XXX most likely self._force_close() has been called, and
|
| 379 |
+
# it has set self._write_fut to None.
|
| 380 |
+
return
|
| 381 |
+
assert f is self._write_fut
|
| 382 |
+
self._write_fut = None
|
| 383 |
+
self._pending_write = 0
|
| 384 |
+
if f:
|
| 385 |
+
f.result()
|
| 386 |
+
if data is None:
|
| 387 |
+
data = self._buffer
|
| 388 |
+
self._buffer = None
|
| 389 |
+
if not data:
|
| 390 |
+
if self._closing:
|
| 391 |
+
self._loop.call_soon(self._call_connection_lost, None)
|
| 392 |
+
if self._eof_written:
|
| 393 |
+
self._sock.shutdown(socket.SHUT_WR)
|
| 394 |
+
# Now that we've reduced the buffer size, tell the
|
| 395 |
+
# protocol to resume writing if it was paused. Note that
|
| 396 |
+
# we do this last since the callback is called immediately
|
| 397 |
+
# and it may add more data to the buffer (even causing the
|
| 398 |
+
# protocol to be paused again).
|
| 399 |
+
self._maybe_resume_protocol()
|
| 400 |
+
else:
|
| 401 |
+
self._write_fut = self._loop._proactor.send(self._sock, data)
|
| 402 |
+
if not self._write_fut.done():
|
| 403 |
+
assert self._pending_write == 0
|
| 404 |
+
self._pending_write = len(data)
|
| 405 |
+
self._write_fut.add_done_callback(self._loop_writing)
|
| 406 |
+
self._maybe_pause_protocol()
|
| 407 |
+
else:
|
| 408 |
+
self._write_fut.add_done_callback(self._loop_writing)
|
| 409 |
+
if self._empty_waiter is not None and self._write_fut is None:
|
| 410 |
+
self._empty_waiter.set_result(None)
|
| 411 |
+
except ConnectionResetError as exc:
|
| 412 |
+
self._force_close(exc)
|
| 413 |
+
except OSError as exc:
|
| 414 |
+
self._fatal_error(exc, 'Fatal write error on pipe transport')
|
| 415 |
+
|
| 416 |
+
def can_write_eof(self):
|
| 417 |
+
return True
|
| 418 |
+
|
| 419 |
+
def write_eof(self):
|
| 420 |
+
self.close()
|
| 421 |
+
|
| 422 |
+
def abort(self):
|
| 423 |
+
self._force_close(None)
|
| 424 |
+
|
| 425 |
+
def _make_empty_waiter(self):
|
| 426 |
+
if self._empty_waiter is not None:
|
| 427 |
+
raise RuntimeError("Empty waiter is already set")
|
| 428 |
+
self._empty_waiter = self._loop.create_future()
|
| 429 |
+
if self._write_fut is None:
|
| 430 |
+
self._empty_waiter.set_result(None)
|
| 431 |
+
return self._empty_waiter
|
| 432 |
+
|
| 433 |
+
def _reset_empty_waiter(self):
|
| 434 |
+
self._empty_waiter = None
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
class _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport):
|
| 438 |
+
def __init__(self, *args, **kw):
|
| 439 |
+
super().__init__(*args, **kw)
|
| 440 |
+
self._read_fut = self._loop._proactor.recv(self._sock, 16)
|
| 441 |
+
self._read_fut.add_done_callback(self._pipe_closed)
|
| 442 |
+
|
| 443 |
+
def _pipe_closed(self, fut):
|
| 444 |
+
if fut.cancelled():
|
| 445 |
+
# the transport has been closed
|
| 446 |
+
return
|
| 447 |
+
assert fut.result() == b''
|
| 448 |
+
if self._closing:
|
| 449 |
+
assert self._read_fut is None
|
| 450 |
+
return
|
| 451 |
+
assert fut is self._read_fut, (fut, self._read_fut)
|
| 452 |
+
self._read_fut = None
|
| 453 |
+
if self._write_fut is not None:
|
| 454 |
+
self._force_close(BrokenPipeError())
|
| 455 |
+
else:
|
| 456 |
+
self.close()
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
class _ProactorDatagramTransport(_ProactorBasePipeTransport,
|
| 460 |
+
transports.DatagramTransport):
|
| 461 |
+
max_size = 256 * 1024
|
| 462 |
+
def __init__(self, loop, sock, protocol, address=None,
|
| 463 |
+
waiter=None, extra=None):
|
| 464 |
+
self._address = address
|
| 465 |
+
self._empty_waiter = None
|
| 466 |
+
self._buffer_size = 0
|
| 467 |
+
# We don't need to call _protocol.connection_made() since our base
|
| 468 |
+
# constructor does it for us.
|
| 469 |
+
super().__init__(loop, sock, protocol, waiter=waiter, extra=extra)
|
| 470 |
+
|
| 471 |
+
# The base constructor sets _buffer = None, so we set it here
|
| 472 |
+
self._buffer = collections.deque()
|
| 473 |
+
self._loop.call_soon(self._loop_reading)
|
| 474 |
+
|
| 475 |
+
def _set_extra(self, sock):
|
| 476 |
+
_set_socket_extra(self, sock)
|
| 477 |
+
|
| 478 |
+
def get_write_buffer_size(self):
|
| 479 |
+
return self._buffer_size
|
| 480 |
+
|
| 481 |
+
def abort(self):
|
| 482 |
+
self._force_close(None)
|
| 483 |
+
|
| 484 |
+
def sendto(self, data, addr=None):
|
| 485 |
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
| 486 |
+
raise TypeError('data argument must be bytes-like object (%r)',
|
| 487 |
+
type(data))
|
| 488 |
+
|
| 489 |
+
if not data:
|
| 490 |
+
return
|
| 491 |
+
|
| 492 |
+
if self._address is not None and addr not in (None, self._address):
|
| 493 |
+
raise ValueError(
|
| 494 |
+
f'Invalid address: must be None or {self._address}')
|
| 495 |
+
|
| 496 |
+
if self._conn_lost and self._address:
|
| 497 |
+
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
|
| 498 |
+
logger.warning('socket.sendto() raised exception.')
|
| 499 |
+
self._conn_lost += 1
|
| 500 |
+
return
|
| 501 |
+
|
| 502 |
+
# Ensure that what we buffer is immutable.
|
| 503 |
+
self._buffer.append((bytes(data), addr))
|
| 504 |
+
self._buffer_size += len(data)
|
| 505 |
+
|
| 506 |
+
if self._write_fut is None:
|
| 507 |
+
# No current write operations are active, kick one off
|
| 508 |
+
self._loop_writing()
|
| 509 |
+
# else: A write operation is already kicked off
|
| 510 |
+
|
| 511 |
+
self._maybe_pause_protocol()
|
| 512 |
+
|
| 513 |
+
def _loop_writing(self, fut=None):
|
| 514 |
+
try:
|
| 515 |
+
if self._conn_lost:
|
| 516 |
+
return
|
| 517 |
+
|
| 518 |
+
assert fut is self._write_fut
|
| 519 |
+
self._write_fut = None
|
| 520 |
+
if fut:
|
| 521 |
+
# We are in a _loop_writing() done callback, get the result
|
| 522 |
+
fut.result()
|
| 523 |
+
|
| 524 |
+
if not self._buffer or (self._conn_lost and self._address):
|
| 525 |
+
# The connection has been closed
|
| 526 |
+
if self._closing:
|
| 527 |
+
self._loop.call_soon(self._call_connection_lost, None)
|
| 528 |
+
return
|
| 529 |
+
|
| 530 |
+
data, addr = self._buffer.popleft()
|
| 531 |
+
self._buffer_size -= len(data)
|
| 532 |
+
if self._address is not None:
|
| 533 |
+
self._write_fut = self._loop._proactor.send(self._sock,
|
| 534 |
+
data)
|
| 535 |
+
else:
|
| 536 |
+
self._write_fut = self._loop._proactor.sendto(self._sock,
|
| 537 |
+
data,
|
| 538 |
+
addr=addr)
|
| 539 |
+
except OSError as exc:
|
| 540 |
+
self._protocol.error_received(exc)
|
| 541 |
+
except Exception as exc:
|
| 542 |
+
self._fatal_error(exc, 'Fatal write error on datagram transport')
|
| 543 |
+
else:
|
| 544 |
+
self._write_fut.add_done_callback(self._loop_writing)
|
| 545 |
+
self._maybe_resume_protocol()
|
| 546 |
+
|
| 547 |
+
def _loop_reading(self, fut=None):
|
| 548 |
+
data = None
|
| 549 |
+
try:
|
| 550 |
+
if self._conn_lost:
|
| 551 |
+
return
|
| 552 |
+
|
| 553 |
+
assert self._read_fut is fut or (self._read_fut is None and
|
| 554 |
+
self._closing)
|
| 555 |
+
|
| 556 |
+
self._read_fut = None
|
| 557 |
+
if fut is not None:
|
| 558 |
+
res = fut.result()
|
| 559 |
+
|
| 560 |
+
if self._closing:
|
| 561 |
+
# since close() has been called we ignore any read data
|
| 562 |
+
data = None
|
| 563 |
+
return
|
| 564 |
+
|
| 565 |
+
if self._address is not None:
|
| 566 |
+
data, addr = res, self._address
|
| 567 |
+
else:
|
| 568 |
+
data, addr = res
|
| 569 |
+
|
| 570 |
+
if self._conn_lost:
|
| 571 |
+
return
|
| 572 |
+
if self._address is not None:
|
| 573 |
+
self._read_fut = self._loop._proactor.recv(self._sock,
|
| 574 |
+
self.max_size)
|
| 575 |
+
else:
|
| 576 |
+
self._read_fut = self._loop._proactor.recvfrom(self._sock,
|
| 577 |
+
self.max_size)
|
| 578 |
+
except OSError as exc:
|
| 579 |
+
self._protocol.error_received(exc)
|
| 580 |
+
except exceptions.CancelledError:
|
| 581 |
+
if not self._closing:
|
| 582 |
+
raise
|
| 583 |
+
else:
|
| 584 |
+
if self._read_fut is not None:
|
| 585 |
+
self._read_fut.add_done_callback(self._loop_reading)
|
| 586 |
+
finally:
|
| 587 |
+
if data:
|
| 588 |
+
self._protocol.datagram_received(data, addr)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
class _ProactorDuplexPipeTransport(_ProactorReadPipeTransport,
|
| 592 |
+
_ProactorBaseWritePipeTransport,
|
| 593 |
+
transports.Transport):
|
| 594 |
+
"""Transport for duplex pipes."""
|
| 595 |
+
|
| 596 |
+
def can_write_eof(self):
|
| 597 |
+
return False
|
| 598 |
+
|
| 599 |
+
def write_eof(self):
|
| 600 |
+
raise NotImplementedError
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
class _ProactorSocketTransport(_ProactorReadPipeTransport,
|
| 604 |
+
_ProactorBaseWritePipeTransport,
|
| 605 |
+
transports.Transport):
|
| 606 |
+
"""Transport for connected sockets."""
|
| 607 |
+
|
| 608 |
+
_sendfile_compatible = constants._SendfileMode.TRY_NATIVE
|
| 609 |
+
|
| 610 |
+
def __init__(self, loop, sock, protocol, waiter=None,
|
| 611 |
+
extra=None, server=None):
|
| 612 |
+
super().__init__(loop, sock, protocol, waiter, extra, server)
|
| 613 |
+
base_events._set_nodelay(sock)
|
| 614 |
+
|
| 615 |
+
def _set_extra(self, sock):
|
| 616 |
+
_set_socket_extra(self, sock)
|
| 617 |
+
|
| 618 |
+
def can_write_eof(self):
|
| 619 |
+
return True
|
| 620 |
+
|
| 621 |
+
def write_eof(self):
|
| 622 |
+
if self._closing or self._eof_written:
|
| 623 |
+
return
|
| 624 |
+
self._eof_written = True
|
| 625 |
+
if self._write_fut is None:
|
| 626 |
+
self._sock.shutdown(socket.SHUT_WR)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
class BaseProactorEventLoop(base_events.BaseEventLoop):
|
| 630 |
+
|
| 631 |
+
def __init__(self, proactor):
|
| 632 |
+
super().__init__()
|
| 633 |
+
logger.debug('Using proactor: %s', proactor.__class__.__name__)
|
| 634 |
+
self._proactor = proactor
|
| 635 |
+
self._selector = proactor # convenient alias
|
| 636 |
+
self._self_reading_future = None
|
| 637 |
+
self._accept_futures = {} # socket file descriptor => Future
|
| 638 |
+
proactor.set_loop(self)
|
| 639 |
+
self._make_self_pipe()
|
| 640 |
+
if threading.current_thread() is threading.main_thread():
|
| 641 |
+
# wakeup fd can only be installed to a file descriptor from the main thread
|
| 642 |
+
signal.set_wakeup_fd(self._csock.fileno())
|
| 643 |
+
|
| 644 |
+
def _make_socket_transport(self, sock, protocol, waiter=None,
|
| 645 |
+
extra=None, server=None):
|
| 646 |
+
return _ProactorSocketTransport(self, sock, protocol, waiter,
|
| 647 |
+
extra, server)
|
| 648 |
+
|
| 649 |
+
def _make_ssl_transport(
|
| 650 |
+
self, rawsock, protocol, sslcontext, waiter=None,
|
| 651 |
+
*, server_side=False, server_hostname=None,
|
| 652 |
+
extra=None, server=None,
|
| 653 |
+
ssl_handshake_timeout=None,
|
| 654 |
+
ssl_shutdown_timeout=None):
|
| 655 |
+
ssl_protocol = sslproto.SSLProtocol(
|
| 656 |
+
self, protocol, sslcontext, waiter,
|
| 657 |
+
server_side, server_hostname,
|
| 658 |
+
ssl_handshake_timeout=ssl_handshake_timeout,
|
| 659 |
+
ssl_shutdown_timeout=ssl_shutdown_timeout)
|
| 660 |
+
_ProactorSocketTransport(self, rawsock, ssl_protocol,
|
| 661 |
+
extra=extra, server=server)
|
| 662 |
+
return ssl_protocol._app_transport
|
| 663 |
+
|
| 664 |
+
def _make_datagram_transport(self, sock, protocol,
|
| 665 |
+
address=None, waiter=None, extra=None):
|
| 666 |
+
return _ProactorDatagramTransport(self, sock, protocol, address,
|
| 667 |
+
waiter, extra)
|
| 668 |
+
|
| 669 |
+
def _make_duplex_pipe_transport(self, sock, protocol, waiter=None,
|
| 670 |
+
extra=None):
|
| 671 |
+
return _ProactorDuplexPipeTransport(self,
|
| 672 |
+
sock, protocol, waiter, extra)
|
| 673 |
+
|
| 674 |
+
def _make_read_pipe_transport(self, sock, protocol, waiter=None,
|
| 675 |
+
extra=None):
|
| 676 |
+
return _ProactorReadPipeTransport(self, sock, protocol, waiter, extra)
|
| 677 |
+
|
| 678 |
+
def _make_write_pipe_transport(self, sock, protocol, waiter=None,
|
| 679 |
+
extra=None):
|
| 680 |
+
# We want connection_lost() to be called when other end closes
|
| 681 |
+
return _ProactorWritePipeTransport(self,
|
| 682 |
+
sock, protocol, waiter, extra)
|
| 683 |
+
|
| 684 |
+
def close(self):
|
| 685 |
+
if self.is_running():
|
| 686 |
+
raise RuntimeError("Cannot close a running event loop")
|
| 687 |
+
if self.is_closed():
|
| 688 |
+
return
|
| 689 |
+
|
| 690 |
+
if threading.current_thread() is threading.main_thread():
|
| 691 |
+
signal.set_wakeup_fd(-1)
|
| 692 |
+
# Call these methods before closing the event loop (before calling
|
| 693 |
+
# BaseEventLoop.close), because they can schedule callbacks with
|
| 694 |
+
# call_soon(), which is forbidden when the event loop is closed.
|
| 695 |
+
self._stop_accept_futures()
|
| 696 |
+
self._close_self_pipe()
|
| 697 |
+
self._proactor.close()
|
| 698 |
+
self._proactor = None
|
| 699 |
+
self._selector = None
|
| 700 |
+
|
| 701 |
+
# Close the event loop
|
| 702 |
+
super().close()
|
| 703 |
+
|
| 704 |
+
async def sock_recv(self, sock, n):
|
| 705 |
+
return await self._proactor.recv(sock, n)
|
| 706 |
+
|
| 707 |
+
async def sock_recv_into(self, sock, buf):
|
| 708 |
+
return await self._proactor.recv_into(sock, buf)
|
| 709 |
+
|
| 710 |
+
async def sock_recvfrom(self, sock, bufsize):
|
| 711 |
+
return await self._proactor.recvfrom(sock, bufsize)
|
| 712 |
+
|
| 713 |
+
async def sock_recvfrom_into(self, sock, buf, nbytes=0):
|
| 714 |
+
if not nbytes:
|
| 715 |
+
nbytes = len(buf)
|
| 716 |
+
|
| 717 |
+
return await self._proactor.recvfrom_into(sock, buf, nbytes)
|
| 718 |
+
|
| 719 |
+
async def sock_sendall(self, sock, data):
|
| 720 |
+
return await self._proactor.send(sock, data)
|
| 721 |
+
|
| 722 |
+
async def sock_sendto(self, sock, data, address):
|
| 723 |
+
return await self._proactor.sendto(sock, data, 0, address)
|
| 724 |
+
|
| 725 |
+
async def sock_connect(self, sock, address):
|
| 726 |
+
return await self._proactor.connect(sock, address)
|
| 727 |
+
|
| 728 |
+
async def sock_accept(self, sock):
|
| 729 |
+
return await self._proactor.accept(sock)
|
| 730 |
+
|
| 731 |
+
async def _sock_sendfile_native(self, sock, file, offset, count):
|
| 732 |
+
try:
|
| 733 |
+
fileno = file.fileno()
|
| 734 |
+
except (AttributeError, io.UnsupportedOperation) as err:
|
| 735 |
+
raise exceptions.SendfileNotAvailableError("not a regular file")
|
| 736 |
+
try:
|
| 737 |
+
fsize = os.fstat(fileno).st_size
|
| 738 |
+
except OSError:
|
| 739 |
+
raise exceptions.SendfileNotAvailableError("not a regular file")
|
| 740 |
+
blocksize = count if count else fsize
|
| 741 |
+
if not blocksize:
|
| 742 |
+
return 0 # empty file
|
| 743 |
+
|
| 744 |
+
blocksize = min(blocksize, 0xffff_ffff)
|
| 745 |
+
end_pos = min(offset + count, fsize) if count else fsize
|
| 746 |
+
offset = min(offset, fsize)
|
| 747 |
+
total_sent = 0
|
| 748 |
+
try:
|
| 749 |
+
while True:
|
| 750 |
+
blocksize = min(end_pos - offset, blocksize)
|
| 751 |
+
if blocksize <= 0:
|
| 752 |
+
return total_sent
|
| 753 |
+
await self._proactor.sendfile(sock, file, offset, blocksize)
|
| 754 |
+
offset += blocksize
|
| 755 |
+
total_sent += blocksize
|
| 756 |
+
finally:
|
| 757 |
+
if total_sent > 0:
|
| 758 |
+
file.seek(offset)
|
| 759 |
+
|
| 760 |
+
async def _sendfile_native(self, transp, file, offset, count):
|
| 761 |
+
resume_reading = transp.is_reading()
|
| 762 |
+
transp.pause_reading()
|
| 763 |
+
await transp._make_empty_waiter()
|
| 764 |
+
try:
|
| 765 |
+
return await self.sock_sendfile(transp._sock, file, offset, count,
|
| 766 |
+
fallback=False)
|
| 767 |
+
finally:
|
| 768 |
+
transp._reset_empty_waiter()
|
| 769 |
+
if resume_reading:
|
| 770 |
+
transp.resume_reading()
|
| 771 |
+
|
| 772 |
+
def _close_self_pipe(self):
|
| 773 |
+
if self._self_reading_future is not None:
|
| 774 |
+
self._self_reading_future.cancel()
|
| 775 |
+
self._self_reading_future = None
|
| 776 |
+
self._ssock.close()
|
| 777 |
+
self._ssock = None
|
| 778 |
+
self._csock.close()
|
| 779 |
+
self._csock = None
|
| 780 |
+
self._internal_fds -= 1
|
| 781 |
+
|
| 782 |
+
def _make_self_pipe(self):
|
| 783 |
+
# A self-socket, really. :-)
|
| 784 |
+
self._ssock, self._csock = socket.socketpair()
|
| 785 |
+
self._ssock.setblocking(False)
|
| 786 |
+
self._csock.setblocking(False)
|
| 787 |
+
self._internal_fds += 1
|
| 788 |
+
|
| 789 |
+
def _loop_self_reading(self, f=None):
|
| 790 |
+
try:
|
| 791 |
+
if f is not None:
|
| 792 |
+
f.result() # may raise
|
| 793 |
+
if self._self_reading_future is not f:
|
| 794 |
+
# When we scheduled this Future, we assigned it to
|
| 795 |
+
# _self_reading_future. If it's not there now, something has
|
| 796 |
+
# tried to cancel the loop while this callback was still in the
|
| 797 |
+
# queue (see windows_events.ProactorEventLoop.run_forever). In
|
| 798 |
+
# that case stop here instead of continuing to schedule a new
|
| 799 |
+
# iteration.
|
| 800 |
+
return
|
| 801 |
+
f = self._proactor.recv(self._ssock, 4096)
|
| 802 |
+
except exceptions.CancelledError:
|
| 803 |
+
# _close_self_pipe() has been called, stop waiting for data
|
| 804 |
+
return
|
| 805 |
+
except (SystemExit, KeyboardInterrupt):
|
| 806 |
+
raise
|
| 807 |
+
except BaseException as exc:
|
| 808 |
+
self.call_exception_handler({
|
| 809 |
+
'message': 'Error on reading from the event loop self pipe',
|
| 810 |
+
'exception': exc,
|
| 811 |
+
'loop': self,
|
| 812 |
+
})
|
| 813 |
+
else:
|
| 814 |
+
self._self_reading_future = f
|
| 815 |
+
f.add_done_callback(self._loop_self_reading)
|
| 816 |
+
|
| 817 |
+
def _write_to_self(self):
|
| 818 |
+
# This may be called from a different thread, possibly after
|
| 819 |
+
# _close_self_pipe() has been called or even while it is
|
| 820 |
+
# running. Guard for self._csock being None or closed. When
|
| 821 |
+
# a socket is closed, send() raises OSError (with errno set to
|
| 822 |
+
# EBADF, but let's not rely on the exact error code).
|
| 823 |
+
csock = self._csock
|
| 824 |
+
if csock is None:
|
| 825 |
+
return
|
| 826 |
+
|
| 827 |
+
try:
|
| 828 |
+
csock.send(b'\0')
|
| 829 |
+
except OSError:
|
| 830 |
+
if self._debug:
|
| 831 |
+
logger.debug("Fail to write a null byte into the "
|
| 832 |
+
"self-pipe socket",
|
| 833 |
+
exc_info=True)
|
| 834 |
+
|
| 835 |
+
def _start_serving(self, protocol_factory, sock,
|
| 836 |
+
sslcontext=None, server=None, backlog=100,
|
| 837 |
+
ssl_handshake_timeout=None,
|
| 838 |
+
ssl_shutdown_timeout=None):
|
| 839 |
+
|
| 840 |
+
def loop(f=None):
|
| 841 |
+
try:
|
| 842 |
+
if f is not None:
|
| 843 |
+
conn, addr = f.result()
|
| 844 |
+
if self._debug:
|
| 845 |
+
logger.debug("%r got a new connection from %r: %r",
|
| 846 |
+
server, addr, conn)
|
| 847 |
+
protocol = protocol_factory()
|
| 848 |
+
if sslcontext is not None:
|
| 849 |
+
self._make_ssl_transport(
|
| 850 |
+
conn, protocol, sslcontext, server_side=True,
|
| 851 |
+
extra={'peername': addr}, server=server,
|
| 852 |
+
ssl_handshake_timeout=ssl_handshake_timeout,
|
| 853 |
+
ssl_shutdown_timeout=ssl_shutdown_timeout)
|
| 854 |
+
else:
|
| 855 |
+
self._make_socket_transport(
|
| 856 |
+
conn, protocol,
|
| 857 |
+
extra={'peername': addr}, server=server)
|
| 858 |
+
if self.is_closed():
|
| 859 |
+
return
|
| 860 |
+
f = self._proactor.accept(sock)
|
| 861 |
+
except OSError as exc:
|
| 862 |
+
if sock.fileno() != -1:
|
| 863 |
+
self.call_exception_handler({
|
| 864 |
+
'message': 'Accept failed on a socket',
|
| 865 |
+
'exception': exc,
|
| 866 |
+
'socket': trsock.TransportSocket(sock),
|
| 867 |
+
})
|
| 868 |
+
sock.close()
|
| 869 |
+
elif self._debug:
|
| 870 |
+
logger.debug("Accept failed on socket %r",
|
| 871 |
+
sock, exc_info=True)
|
| 872 |
+
except exceptions.CancelledError:
|
| 873 |
+
sock.close()
|
| 874 |
+
else:
|
| 875 |
+
self._accept_futures[sock.fileno()] = f
|
| 876 |
+
f.add_done_callback(loop)
|
| 877 |
+
|
| 878 |
+
self.call_soon(loop)
|
| 879 |
+
|
| 880 |
+
def _process_events(self, event_list):
|
| 881 |
+
# Events are processed in the IocpProactor._poll() method
|
| 882 |
+
pass
|
| 883 |
+
|
| 884 |
+
def _stop_accept_futures(self):
|
| 885 |
+
for future in self._accept_futures.values():
|
| 886 |
+
future.cancel()
|
| 887 |
+
self._accept_futures.clear()
|
| 888 |
+
|
| 889 |
+
def _stop_serving(self, sock):
|
| 890 |
+
future = self._accept_futures.pop(sock.fileno(), None)
|
| 891 |
+
if future:
|
| 892 |
+
future.cancel()
|
| 893 |
+
self._proactor._stop_serving(sock)
|
| 894 |
+
sock.close()
|
micromamba_root/envs/pytorch_env/Lib/asyncio/protocols.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Abstract Protocol base classes."""
|
| 2 |
+
|
| 3 |
+
__all__ = (
|
| 4 |
+
'BaseProtocol', 'Protocol', 'DatagramProtocol',
|
| 5 |
+
'SubprocessProtocol', 'BufferedProtocol',
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class BaseProtocol:
|
| 10 |
+
"""Common base class for protocol interfaces.
|
| 11 |
+
|
| 12 |
+
Usually user implements protocols that derived from BaseProtocol
|
| 13 |
+
like Protocol or ProcessProtocol.
|
| 14 |
+
|
| 15 |
+
The only case when BaseProtocol should be implemented directly is
|
| 16 |
+
write-only transport like write pipe
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
__slots__ = ()
|
| 20 |
+
|
| 21 |
+
def connection_made(self, transport):
|
| 22 |
+
"""Called when a connection is made.
|
| 23 |
+
|
| 24 |
+
The argument is the transport representing the pipe connection.
|
| 25 |
+
To receive data, wait for data_received() calls.
|
| 26 |
+
When the connection is closed, connection_lost() is called.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def connection_lost(self, exc):
|
| 30 |
+
"""Called when the connection is lost or closed.
|
| 31 |
+
|
| 32 |
+
The argument is an exception object or None (the latter
|
| 33 |
+
meaning a regular EOF is received or the connection was
|
| 34 |
+
aborted or closed).
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def pause_writing(self):
|
| 38 |
+
"""Called when the transport's buffer goes over the high-water mark.
|
| 39 |
+
|
| 40 |
+
Pause and resume calls are paired -- pause_writing() is called
|
| 41 |
+
once when the buffer goes strictly over the high-water mark
|
| 42 |
+
(even if subsequent writes increases the buffer size even
|
| 43 |
+
more), and eventually resume_writing() is called once when the
|
| 44 |
+
buffer size reaches the low-water mark.
|
| 45 |
+
|
| 46 |
+
Note that if the buffer size equals the high-water mark,
|
| 47 |
+
pause_writing() is not called -- it must go strictly over.
|
| 48 |
+
Conversely, resume_writing() is called when the buffer size is
|
| 49 |
+
equal or lower than the low-water mark. These end conditions
|
| 50 |
+
are important to ensure that things go as expected when either
|
| 51 |
+
mark is zero.
|
| 52 |
+
|
| 53 |
+
NOTE: This is the only Protocol callback that is not called
|
| 54 |
+
through EventLoop.call_soon() -- if it were, it would have no
|
| 55 |
+
effect when it's most needed (when the app keeps writing
|
| 56 |
+
without yielding until pause_writing() is called).
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
def resume_writing(self):
|
| 60 |
+
"""Called when the transport's buffer drains below the low-water mark.
|
| 61 |
+
|
| 62 |
+
See pause_writing() for details.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class Protocol(BaseProtocol):
|
| 67 |
+
"""Interface for stream protocol.
|
| 68 |
+
|
| 69 |
+
The user should implement this interface. They can inherit from
|
| 70 |
+
this class but don't need to. The implementations here do
|
| 71 |
+
nothing (they don't raise exceptions).
|
| 72 |
+
|
| 73 |
+
When the user wants to requests a transport, they pass a protocol
|
| 74 |
+
factory to a utility function (e.g., EventLoop.create_connection()).
|
| 75 |
+
|
| 76 |
+
When the connection is made successfully, connection_made() is
|
| 77 |
+
called with a suitable transport object. Then data_received()
|
| 78 |
+
will be called 0 or more times with data (bytes) received from the
|
| 79 |
+
transport; finally, connection_lost() will be called exactly once
|
| 80 |
+
with either an exception object or None as an argument.
|
| 81 |
+
|
| 82 |
+
State machine of calls:
|
| 83 |
+
|
| 84 |
+
start -> CM [-> DR*] [-> ER?] -> CL -> end
|
| 85 |
+
|
| 86 |
+
* CM: connection_made()
|
| 87 |
+
* DR: data_received()
|
| 88 |
+
* ER: eof_received()
|
| 89 |
+
* CL: connection_lost()
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
__slots__ = ()
|
| 93 |
+
|
| 94 |
+
def data_received(self, data):
|
| 95 |
+
"""Called when some data is received.
|
| 96 |
+
|
| 97 |
+
The argument is a bytes object.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def eof_received(self):
|
| 101 |
+
"""Called when the other end calls write_eof() or equivalent.
|
| 102 |
+
|
| 103 |
+
If this returns a false value (including None), the transport
|
| 104 |
+
will close itself. If it returns a true value, closing the
|
| 105 |
+
transport is up to the protocol.
|
| 106 |
+
"""
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class BufferedProtocol(BaseProtocol):
|
| 110 |
+
"""Interface for stream protocol with manual buffer control.
|
| 111 |
+
|
| 112 |
+
Event methods, such as `create_server` and `create_connection`,
|
| 113 |
+
accept factories that return protocols that implement this interface.
|
| 114 |
+
|
| 115 |
+
The idea of BufferedProtocol is that it allows to manually allocate
|
| 116 |
+
and control the receive buffer. Event loops can then use the buffer
|
| 117 |
+
provided by the protocol to avoid unnecessary data copies. This
|
| 118 |
+
can result in noticeable performance improvement for protocols that
|
| 119 |
+
receive big amounts of data. Sophisticated protocols can allocate
|
| 120 |
+
the buffer only once at creation time.
|
| 121 |
+
|
| 122 |
+
State machine of calls:
|
| 123 |
+
|
| 124 |
+
start -> CM [-> GB [-> BU?]]* [-> ER?] -> CL -> end
|
| 125 |
+
|
| 126 |
+
* CM: connection_made()
|
| 127 |
+
* GB: get_buffer()
|
| 128 |
+
* BU: buffer_updated()
|
| 129 |
+
* ER: eof_received()
|
| 130 |
+
* CL: connection_lost()
|
| 131 |
+
"""
|
| 132 |
+
|
| 133 |
+
__slots__ = ()
|
| 134 |
+
|
| 135 |
+
def get_buffer(self, sizehint):
|
| 136 |
+
"""Called to allocate a new receive buffer.
|
| 137 |
+
|
| 138 |
+
*sizehint* is a recommended minimal size for the returned
|
| 139 |
+
buffer. When set to -1, the buffer size can be arbitrary.
|
| 140 |
+
|
| 141 |
+
Must return an object that implements the
|
| 142 |
+
:ref:`buffer protocol <bufferobjects>`.
|
| 143 |
+
It is an error to return a zero-sized buffer.
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
def buffer_updated(self, nbytes):
|
| 147 |
+
"""Called when the buffer was updated with the received data.
|
| 148 |
+
|
| 149 |
+
*nbytes* is the total number of bytes that were written to
|
| 150 |
+
the buffer.
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
def eof_received(self):
|
| 154 |
+
"""Called when the other end calls write_eof() or equivalent.
|
| 155 |
+
|
| 156 |
+
If this returns a false value (including None), the transport
|
| 157 |
+
will close itself. If it returns a true value, closing the
|
| 158 |
+
transport is up to the protocol.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class DatagramProtocol(BaseProtocol):
|
| 163 |
+
"""Interface for datagram protocol."""
|
| 164 |
+
|
| 165 |
+
__slots__ = ()
|
| 166 |
+
|
| 167 |
+
def datagram_received(self, data, addr):
|
| 168 |
+
"""Called when some datagram is received."""
|
| 169 |
+
|
| 170 |
+
def error_received(self, exc):
|
| 171 |
+
"""Called when a send or receive operation raises an OSError.
|
| 172 |
+
|
| 173 |
+
(Other than BlockingIOError or InterruptedError.)
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class SubprocessProtocol(BaseProtocol):
|
| 178 |
+
"""Interface for protocol for subprocess calls."""
|
| 179 |
+
|
| 180 |
+
__slots__ = ()
|
| 181 |
+
|
| 182 |
+
def pipe_data_received(self, fd, data):
|
| 183 |
+
"""Called when the subprocess writes data into stdout/stderr pipe.
|
| 184 |
+
|
| 185 |
+
fd is int file descriptor.
|
| 186 |
+
data is bytes object.
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
def pipe_connection_lost(self, fd, exc):
|
| 190 |
+
"""Called when a file descriptor associated with the child process is
|
| 191 |
+
closed.
|
| 192 |
+
|
| 193 |
+
fd is the int file descriptor that was closed.
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
def process_exited(self):
|
| 197 |
+
"""Called when subprocess has exited."""
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _feed_data_to_buffered_proto(proto, data):
|
| 201 |
+
data_len = len(data)
|
| 202 |
+
while data_len:
|
| 203 |
+
buf = proto.get_buffer(data_len)
|
| 204 |
+
buf_len = len(buf)
|
| 205 |
+
if not buf_len:
|
| 206 |
+
raise RuntimeError('get_buffer() returned an empty buffer')
|
| 207 |
+
|
| 208 |
+
if buf_len >= data_len:
|
| 209 |
+
buf[:data_len] = data
|
| 210 |
+
proto.buffer_updated(data_len)
|
| 211 |
+
return
|
| 212 |
+
else:
|
| 213 |
+
buf[:buf_len] = data[:buf_len]
|
| 214 |
+
proto.buffer_updated(buf_len)
|
| 215 |
+
data = data[buf_len:]
|
| 216 |
+
data_len = len(data)
|
micromamba_root/envs/pytorch_env/Lib/asyncio/queues.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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from . import locks
|
| 8 |
+
from . import mixins
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class QueueEmpty(Exception):
|
| 12 |
+
"""Raised when Queue.get_nowait() is called on an empty Queue."""
|
| 13 |
+
pass
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class QueueFull(Exception):
|
| 17 |
+
"""Raised when the Queue.put_nowait() method is called on a full Queue."""
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Queue(mixins._LoopBoundMixin):
|
| 22 |
+
"""A queue, useful for coordinating producer and consumer coroutines.
|
| 23 |
+
|
| 24 |
+
If maxsize is less than or equal to zero, the queue size is infinite. If it
|
| 25 |
+
is an integer greater than 0, then "await put()" will block when the
|
| 26 |
+
queue reaches maxsize, until an item is removed by get().
|
| 27 |
+
|
| 28 |
+
Unlike the standard library Queue, you can reliably know this Queue's size
|
| 29 |
+
with qsize(), since your single-threaded asyncio application won't be
|
| 30 |
+
interrupted between calling qsize() and doing an operation on the Queue.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, maxsize=0):
|
| 34 |
+
self._maxsize = maxsize
|
| 35 |
+
|
| 36 |
+
# Futures.
|
| 37 |
+
self._getters = collections.deque()
|
| 38 |
+
# Futures.
|
| 39 |
+
self._putters = collections.deque()
|
| 40 |
+
self._unfinished_tasks = 0
|
| 41 |
+
self._finished = locks.Event()
|
| 42 |
+
self._finished.set()
|
| 43 |
+
self._init(maxsize)
|
| 44 |
+
|
| 45 |
+
# These three are overridable in subclasses.
|
| 46 |
+
|
| 47 |
+
def _init(self, maxsize):
|
| 48 |
+
self._queue = collections.deque()
|
| 49 |
+
|
| 50 |
+
def _get(self):
|
| 51 |
+
return self._queue.popleft()
|
| 52 |
+
|
| 53 |
+
def _put(self, item):
|
| 54 |
+
self._queue.append(item)
|
| 55 |
+
|
| 56 |
+
# End of the overridable methods.
|
| 57 |
+
|
| 58 |
+
def _wakeup_next(self, waiters):
|
| 59 |
+
# Wake up the next waiter (if any) that isn't cancelled.
|
| 60 |
+
while waiters:
|
| 61 |
+
waiter = waiters.popleft()
|
| 62 |
+
if not waiter.done():
|
| 63 |
+
waiter.set_result(None)
|
| 64 |
+
break
|
| 65 |
+
|
| 66 |
+
def __repr__(self):
|
| 67 |
+
return f'<{type(self).__name__} at {id(self):#x} {self._format()}>'
|
| 68 |
+
|
| 69 |
+
def __str__(self):
|
| 70 |
+
return f'<{type(self).__name__} {self._format()}>'
|
| 71 |
+
|
| 72 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 73 |
+
|
| 74 |
+
def _format(self):
|
| 75 |
+
result = f'maxsize={self._maxsize!r}'
|
| 76 |
+
if getattr(self, '_queue', None):
|
| 77 |
+
result += f' _queue={list(self._queue)!r}'
|
| 78 |
+
if self._getters:
|
| 79 |
+
result += f' _getters[{len(self._getters)}]'
|
| 80 |
+
if self._putters:
|
| 81 |
+
result += f' _putters[{len(self._putters)}]'
|
| 82 |
+
if self._unfinished_tasks:
|
| 83 |
+
result += f' tasks={self._unfinished_tasks}'
|
| 84 |
+
return result
|
| 85 |
+
|
| 86 |
+
def qsize(self):
|
| 87 |
+
"""Number of items in the queue."""
|
| 88 |
+
return len(self._queue)
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def maxsize(self):
|
| 92 |
+
"""Number of items allowed in the queue."""
|
| 93 |
+
return self._maxsize
|
| 94 |
+
|
| 95 |
+
def empty(self):
|
| 96 |
+
"""Return True if the queue is empty, False otherwise."""
|
| 97 |
+
return not self._queue
|
| 98 |
+
|
| 99 |
+
def full(self):
|
| 100 |
+
"""Return True if there are maxsize items in the queue.
|
| 101 |
+
|
| 102 |
+
Note: if the Queue was initialized with maxsize=0 (the default),
|
| 103 |
+
then full() is never True.
|
| 104 |
+
"""
|
| 105 |
+
if self._maxsize <= 0:
|
| 106 |
+
return False
|
| 107 |
+
else:
|
| 108 |
+
return self.qsize() >= self._maxsize
|
| 109 |
+
|
| 110 |
+
async def put(self, item):
|
| 111 |
+
"""Put an item into the queue.
|
| 112 |
+
|
| 113 |
+
Put an item into the queue. If the queue is full, wait until a free
|
| 114 |
+
slot is available before adding item.
|
| 115 |
+
"""
|
| 116 |
+
while self.full():
|
| 117 |
+
putter = self._get_loop().create_future()
|
| 118 |
+
self._putters.append(putter)
|
| 119 |
+
try:
|
| 120 |
+
await putter
|
| 121 |
+
except:
|
| 122 |
+
putter.cancel() # Just in case putter is not done yet.
|
| 123 |
+
try:
|
| 124 |
+
# Clean self._putters from canceled putters.
|
| 125 |
+
self._putters.remove(putter)
|
| 126 |
+
except ValueError:
|
| 127 |
+
# The putter could be removed from self._putters by a
|
| 128 |
+
# previous get_nowait call.
|
| 129 |
+
pass
|
| 130 |
+
if not self.full() and not putter.cancelled():
|
| 131 |
+
# We were woken up by get_nowait(), but can't take
|
| 132 |
+
# the call. Wake up the next in line.
|
| 133 |
+
self._wakeup_next(self._putters)
|
| 134 |
+
raise
|
| 135 |
+
return self.put_nowait(item)
|
| 136 |
+
|
| 137 |
+
def put_nowait(self, item):
|
| 138 |
+
"""Put an item into the queue without blocking.
|
| 139 |
+
|
| 140 |
+
If no free slot is immediately available, raise QueueFull.
|
| 141 |
+
"""
|
| 142 |
+
if self.full():
|
| 143 |
+
raise QueueFull
|
| 144 |
+
self._put(item)
|
| 145 |
+
self._unfinished_tasks += 1
|
| 146 |
+
self._finished.clear()
|
| 147 |
+
self._wakeup_next(self._getters)
|
| 148 |
+
|
| 149 |
+
async def get(self):
|
| 150 |
+
"""Remove and return an item from the queue.
|
| 151 |
+
|
| 152 |
+
If queue is empty, wait until an item is available.
|
| 153 |
+
"""
|
| 154 |
+
while self.empty():
|
| 155 |
+
getter = self._get_loop().create_future()
|
| 156 |
+
self._getters.append(getter)
|
| 157 |
+
try:
|
| 158 |
+
await getter
|
| 159 |
+
except:
|
| 160 |
+
getter.cancel() # Just in case getter is not done yet.
|
| 161 |
+
try:
|
| 162 |
+
# Clean self._getters from canceled getters.
|
| 163 |
+
self._getters.remove(getter)
|
| 164 |
+
except ValueError:
|
| 165 |
+
# The getter could be removed from self._getters by a
|
| 166 |
+
# previous put_nowait call.
|
| 167 |
+
pass
|
| 168 |
+
if not self.empty() and not getter.cancelled():
|
| 169 |
+
# We were woken up by put_nowait(), but can't take
|
| 170 |
+
# the call. Wake up the next in line.
|
| 171 |
+
self._wakeup_next(self._getters)
|
| 172 |
+
raise
|
| 173 |
+
return self.get_nowait()
|
| 174 |
+
|
| 175 |
+
def get_nowait(self):
|
| 176 |
+
"""Remove and return an item from the queue.
|
| 177 |
+
|
| 178 |
+
Return an item if one is immediately available, else raise QueueEmpty.
|
| 179 |
+
"""
|
| 180 |
+
if self.empty():
|
| 181 |
+
raise QueueEmpty
|
| 182 |
+
item = self._get()
|
| 183 |
+
self._wakeup_next(self._putters)
|
| 184 |
+
return item
|
| 185 |
+
|
| 186 |
+
def task_done(self):
|
| 187 |
+
"""Indicate that a formerly enqueued task is complete.
|
| 188 |
+
|
| 189 |
+
Used by queue consumers. For each get() used to fetch a task,
|
| 190 |
+
a subsequent call to task_done() tells the queue that the processing
|
| 191 |
+
on the task is complete.
|
| 192 |
+
|
| 193 |
+
If a join() is currently blocking, it will resume when all items have
|
| 194 |
+
been processed (meaning that a task_done() call was received for every
|
| 195 |
+
item that had been put() into the queue).
|
| 196 |
+
|
| 197 |
+
Raises ValueError if called more times than there were items placed in
|
| 198 |
+
the queue.
|
| 199 |
+
"""
|
| 200 |
+
if self._unfinished_tasks <= 0:
|
| 201 |
+
raise ValueError('task_done() called too many times')
|
| 202 |
+
self._unfinished_tasks -= 1
|
| 203 |
+
if self._unfinished_tasks == 0:
|
| 204 |
+
self._finished.set()
|
| 205 |
+
|
| 206 |
+
async def join(self):
|
| 207 |
+
"""Block until all items in the queue have been gotten and processed.
|
| 208 |
+
|
| 209 |
+
The count of unfinished tasks goes up whenever an item is added to the
|
| 210 |
+
queue. The count goes down whenever a consumer calls task_done() to
|
| 211 |
+
indicate that the item was retrieved and all work on it is complete.
|
| 212 |
+
When the count of unfinished tasks drops to zero, join() unblocks.
|
| 213 |
+
"""
|
| 214 |
+
if self._unfinished_tasks > 0:
|
| 215 |
+
await self._finished.wait()
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class PriorityQueue(Queue):
|
| 219 |
+
"""A subclass of Queue; retrieves entries in priority order (lowest first).
|
| 220 |
+
|
| 221 |
+
Entries are typically tuples of the form: (priority number, data).
|
| 222 |
+
"""
|
| 223 |
+
|
| 224 |
+
def _init(self, maxsize):
|
| 225 |
+
self._queue = []
|
| 226 |
+
|
| 227 |
+
def _put(self, item, heappush=heapq.heappush):
|
| 228 |
+
heappush(self._queue, item)
|
| 229 |
+
|
| 230 |
+
def _get(self, heappop=heapq.heappop):
|
| 231 |
+
return heappop(self._queue)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class LifoQueue(Queue):
|
| 235 |
+
"""A subclass of Queue that retrieves most recently added entries first."""
|
| 236 |
+
|
| 237 |
+
def _init(self, maxsize):
|
| 238 |
+
self._queue = []
|
| 239 |
+
|
| 240 |
+
def _put(self, item):
|
| 241 |
+
self._queue.append(item)
|
| 242 |
+
|
| 243 |
+
def _get(self):
|
| 244 |
+
return self._queue.pop()
|
micromamba_root/envs/pytorch_env/Lib/asyncio/runners.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 7 |
+
import signal
|
| 8 |
+
import sys
|
| 9 |
+
from . import coroutines
|
| 10 |
+
from . import events
|
| 11 |
+
from . import exceptions
|
| 12 |
+
from . import tasks
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class _State(enum.Enum):
|
| 16 |
+
CREATED = "created"
|
| 17 |
+
INITIALIZED = "initialized"
|
| 18 |
+
CLOSED = "closed"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class Runner:
|
| 22 |
+
"""A context manager that controls event loop life cycle.
|
| 23 |
+
|
| 24 |
+
The context manager always creates a new event loop,
|
| 25 |
+
allows to run async functions inside it,
|
| 26 |
+
and properly finalizes the loop at the context manager exit.
|
| 27 |
+
|
| 28 |
+
If debug is True, the event loop will be run in debug mode.
|
| 29 |
+
If loop_factory is passed, it is used for new event loop creation.
|
| 30 |
+
|
| 31 |
+
asyncio.run(main(), debug=True)
|
| 32 |
+
|
| 33 |
+
is a shortcut for
|
| 34 |
+
|
| 35 |
+
with asyncio.Runner(debug=True) as runner:
|
| 36 |
+
runner.run(main())
|
| 37 |
+
|
| 38 |
+
The run() method can be called multiple times within the runner's context.
|
| 39 |
+
|
| 40 |
+
This can be useful for interactive console (e.g. IPython),
|
| 41 |
+
unittest runners, console tools, -- everywhere when async code
|
| 42 |
+
is called from existing sync framework and where the preferred single
|
| 43 |
+
asyncio.run() call doesn't work.
|
| 44 |
+
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
# Note: the class is final, it is not intended for inheritance.
|
| 48 |
+
|
| 49 |
+
def __init__(self, *, debug=None, loop_factory=None):
|
| 50 |
+
self._state = _State.CREATED
|
| 51 |
+
self._debug = debug
|
| 52 |
+
self._loop_factory = loop_factory
|
| 53 |
+
self._loop = None
|
| 54 |
+
self._context = None
|
| 55 |
+
self._interrupt_count = 0
|
| 56 |
+
self._set_event_loop = False
|
| 57 |
+
|
| 58 |
+
def __enter__(self):
|
| 59 |
+
self._lazy_init()
|
| 60 |
+
return self
|
| 61 |
+
|
| 62 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 63 |
+
self.close()
|
| 64 |
+
|
| 65 |
+
def close(self):
|
| 66 |
+
"""Shutdown and close event loop."""
|
| 67 |
+
if self._state is not _State.INITIALIZED:
|
| 68 |
+
return
|
| 69 |
+
try:
|
| 70 |
+
loop = self._loop
|
| 71 |
+
_cancel_all_tasks(loop)
|
| 72 |
+
loop.run_until_complete(loop.shutdown_asyncgens())
|
| 73 |
+
loop.run_until_complete(loop.shutdown_default_executor())
|
| 74 |
+
finally:
|
| 75 |
+
if self._set_event_loop:
|
| 76 |
+
events.set_event_loop(None)
|
| 77 |
+
loop.close()
|
| 78 |
+
self._loop = None
|
| 79 |
+
self._state = _State.CLOSED
|
| 80 |
+
|
| 81 |
+
def get_loop(self):
|
| 82 |
+
"""Return embedded event loop."""
|
| 83 |
+
self._lazy_init()
|
| 84 |
+
return self._loop
|
| 85 |
+
|
| 86 |
+
def run(self, coro, *, context=None):
|
| 87 |
+
"""Run a coroutine inside the embedded event loop."""
|
| 88 |
+
if not coroutines.iscoroutine(coro):
|
| 89 |
+
raise ValueError("a coroutine was expected, got {!r}".format(coro))
|
| 90 |
+
|
| 91 |
+
if events._get_running_loop() is not None:
|
| 92 |
+
# fail fast with short traceback
|
| 93 |
+
raise RuntimeError(
|
| 94 |
+
"Runner.run() cannot be called from a running event loop")
|
| 95 |
+
|
| 96 |
+
self._lazy_init()
|
| 97 |
+
|
| 98 |
+
if context is None:
|
| 99 |
+
context = self._context
|
| 100 |
+
task = self._loop.create_task(coro, context=context)
|
| 101 |
+
|
| 102 |
+
if (threading.current_thread() is threading.main_thread()
|
| 103 |
+
and signal.getsignal(signal.SIGINT) is signal.default_int_handler
|
| 104 |
+
):
|
| 105 |
+
sigint_handler = functools.partial(self._on_sigint, main_task=task)
|
| 106 |
+
try:
|
| 107 |
+
signal.signal(signal.SIGINT, sigint_handler)
|
| 108 |
+
except ValueError:
|
| 109 |
+
# `signal.signal` may throw if `threading.main_thread` does
|
| 110 |
+
# not support signals (e.g. embedded interpreter with signals
|
| 111 |
+
# not registered - see gh-91880)
|
| 112 |
+
sigint_handler = None
|
| 113 |
+
else:
|
| 114 |
+
sigint_handler = None
|
| 115 |
+
|
| 116 |
+
self._interrupt_count = 0
|
| 117 |
+
try:
|
| 118 |
+
return self._loop.run_until_complete(task)
|
| 119 |
+
except exceptions.CancelledError:
|
| 120 |
+
if self._interrupt_count > 0:
|
| 121 |
+
uncancel = getattr(task, "uncancel", None)
|
| 122 |
+
if uncancel is not None and uncancel() == 0:
|
| 123 |
+
raise KeyboardInterrupt()
|
| 124 |
+
raise # CancelledError
|
| 125 |
+
finally:
|
| 126 |
+
if (sigint_handler is not None
|
| 127 |
+
and signal.getsignal(signal.SIGINT) is sigint_handler
|
| 128 |
+
):
|
| 129 |
+
signal.signal(signal.SIGINT, signal.default_int_handler)
|
| 130 |
+
|
| 131 |
+
def _lazy_init(self):
|
| 132 |
+
if self._state is _State.CLOSED:
|
| 133 |
+
raise RuntimeError("Runner is closed")
|
| 134 |
+
if self._state is _State.INITIALIZED:
|
| 135 |
+
return
|
| 136 |
+
if self._loop_factory is None:
|
| 137 |
+
self._loop = events.new_event_loop()
|
| 138 |
+
if not self._set_event_loop:
|
| 139 |
+
# Call set_event_loop only once to avoid calling
|
| 140 |
+
# attach_loop multiple times on child watchers
|
| 141 |
+
events.set_event_loop(self._loop)
|
| 142 |
+
self._set_event_loop = True
|
| 143 |
+
else:
|
| 144 |
+
self._loop = self._loop_factory()
|
| 145 |
+
if self._debug is not None:
|
| 146 |
+
self._loop.set_debug(self._debug)
|
| 147 |
+
self._context = contextvars.copy_context()
|
| 148 |
+
self._state = _State.INITIALIZED
|
| 149 |
+
|
| 150 |
+
def _on_sigint(self, signum, frame, main_task):
|
| 151 |
+
self._interrupt_count += 1
|
| 152 |
+
if self._interrupt_count == 1 and not main_task.done():
|
| 153 |
+
main_task.cancel()
|
| 154 |
+
# wakeup loop if it is blocked by select() with long timeout
|
| 155 |
+
self._loop.call_soon_threadsafe(lambda: None)
|
| 156 |
+
return
|
| 157 |
+
raise KeyboardInterrupt()
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def run(main, *, debug=None):
|
| 161 |
+
"""Execute the coroutine and return the result.
|
| 162 |
+
|
| 163 |
+
This function runs the passed coroutine, taking care of
|
| 164 |
+
managing the asyncio event loop and finalizing asynchronous
|
| 165 |
+
generators.
|
| 166 |
+
|
| 167 |
+
This function cannot be called when another asyncio event loop is
|
| 168 |
+
running in the same thread.
|
| 169 |
+
|
| 170 |
+
If debug is True, the event loop will be run in debug mode.
|
| 171 |
+
|
| 172 |
+
This function always creates a new event loop and closes it at the end.
|
| 173 |
+
It should be used as a main entry point for asyncio programs, and should
|
| 174 |
+
ideally only be called once.
|
| 175 |
+
|
| 176 |
+
Example:
|
| 177 |
+
|
| 178 |
+
async def main():
|
| 179 |
+
await asyncio.sleep(1)
|
| 180 |
+
print('hello')
|
| 181 |
+
|
| 182 |
+
asyncio.run(main())
|
| 183 |
+
"""
|
| 184 |
+
if events._get_running_loop() is not None:
|
| 185 |
+
# fail fast with short traceback
|
| 186 |
+
raise RuntimeError(
|
| 187 |
+
"asyncio.run() cannot be called from a running event loop")
|
| 188 |
+
|
| 189 |
+
with Runner(debug=debug) as runner:
|
| 190 |
+
return runner.run(main)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _cancel_all_tasks(loop):
|
| 194 |
+
to_cancel = tasks.all_tasks(loop)
|
| 195 |
+
if not to_cancel:
|
| 196 |
+
return
|
| 197 |
+
|
| 198 |
+
for task in to_cancel:
|
| 199 |
+
task.cancel()
|
| 200 |
+
|
| 201 |
+
loop.run_until_complete(tasks.gather(*to_cancel, return_exceptions=True))
|
| 202 |
+
|
| 203 |
+
for task in to_cancel:
|
| 204 |
+
if task.cancelled():
|
| 205 |
+
continue
|
| 206 |
+
if task.exception() is not None:
|
| 207 |
+
loop.call_exception_handler({
|
| 208 |
+
'message': 'unhandled exception during asyncio.run() sh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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event loop using a selector and related classes.
|
| 2 |
+
|
| 3 |
+
A selector is a "notify-when-ready" multiplexer. For a subclass which
|
| 4 |
+
also includes support for signal handling, see the unix_events sub-module.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
__all__ = 'BaseSelectorEventLoop',
|
| 8 |
+
|
| 9 |
+
import collections
|
| 10 |
+
import errno
|
| 11 |
+
import functools
|
| 12 |
+
import selectors
|
| 13 |
+
import socket
|
| 14 |
+
import warnings
|
| 15 |
+
import weakref
|
| 16 |
+
try:
|
| 17 |
+
import ssl
|
| 18 |
+
except ImportError: # pragma: no cover
|
| 19 |
+
ssl = None
|
| 20 |
+
|
| 21 |
+
from . import base_events
|
| 22 |
+
from . import constants
|
| 23 |
+
from . import events
|
| 24 |
+
from . import futures
|
| 25 |
+
from . import protocols
|
| 26 |
+
from . import sslproto
|
| 27 |
+
from . import transports
|
| 28 |
+
from . import trsock
|
| 29 |
+
from .log import logger
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _test_selector_event(selector, fd, event):
|
| 33 |
+
# Test if the selector is monitoring 'event' events
|
| 34 |
+
# for the file descriptor 'fd'.
|
| 35 |
+
try:
|
| 36 |
+
key = selector.get_key(fd)
|
| 37 |
+
except KeyError:
|
| 38 |
+
return False
|
| 39 |
+
else:
|
| 40 |
+
return bool(key.events & event)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class BaseSelectorEventLoop(base_events.BaseEventLoop):
|
| 44 |
+
"""Selector event loop.
|
| 45 |
+
|
| 46 |
+
See events.EventLoop for API specification.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def __init__(self, selector=None):
|
| 50 |
+
super().__init__()
|
| 51 |
+
|
| 52 |
+
if selector is None:
|
| 53 |
+
selector = selectors.DefaultSelector()
|
| 54 |
+
logger.debug('Using selector: %s', selector.__class__.__name__)
|
| 55 |
+
self._selector = selector
|
| 56 |
+
self._make_self_pipe()
|
| 57 |
+
self._transports = weakref.WeakValueDictionary()
|
| 58 |
+
|
| 59 |
+
def _make_socket_transport(self, sock, protocol, waiter=None, *,
|
| 60 |
+
extra=None, server=None):
|
| 61 |
+
return _SelectorSocketTransport(self, sock, protocol, waiter,
|
| 62 |
+
extra, server)
|
| 63 |
+
|
| 64 |
+
def _make_ssl_transport(
|
| 65 |
+
self, rawsock, protocol, sslcontext, waiter=None,
|
| 66 |
+
*, server_side=False, server_hostname=None,
|
| 67 |
+
extra=None, server=None,
|
| 68 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT,
|
| 69 |
+
ssl_shutdown_timeout=constants.SSL_SHUTDOWN_TIMEOUT,
|
| 70 |
+
):
|
| 71 |
+
ssl_protocol = sslproto.SSLProtocol(
|
| 72 |
+
self, protocol, sslcontext, waiter,
|
| 73 |
+
server_side, server_hostname,
|
| 74 |
+
ssl_handshake_timeout=ssl_handshake_timeout,
|
| 75 |
+
ssl_shutdown_timeout=ssl_shutdown_timeout
|
| 76 |
+
)
|
| 77 |
+
_SelectorSocketTransport(self, rawsock, ssl_protocol,
|
| 78 |
+
extra=extra, server=server)
|
| 79 |
+
return ssl_protocol._app_transport
|
| 80 |
+
|
| 81 |
+
def _make_datagram_transport(self, sock, protocol,
|
| 82 |
+
address=None, waiter=None, extra=None):
|
| 83 |
+
return _SelectorDatagramTransport(self, sock, protocol,
|
| 84 |
+
address, waiter, extra)
|
| 85 |
+
|
| 86 |
+
def close(self):
|
| 87 |
+
if self.is_running():
|
| 88 |
+
raise RuntimeError("Cannot close a running event loop")
|
| 89 |
+
if self.is_closed():
|
| 90 |
+
return
|
| 91 |
+
self._close_self_pipe()
|
| 92 |
+
super().close()
|
| 93 |
+
if self._selector is not None:
|
| 94 |
+
self._selector.close()
|
| 95 |
+
self._selector = None
|
| 96 |
+
|
| 97 |
+
def _close_self_pipe(self):
|
| 98 |
+
self._remove_reader(self._ssock.fileno())
|
| 99 |
+
self._ssock.close()
|
| 100 |
+
self._ssock = None
|
| 101 |
+
self._csock.close()
|
| 102 |
+
self._csock = None
|
| 103 |
+
self._internal_fds -= 1
|
| 104 |
+
|
| 105 |
+
def _make_self_pipe(self):
|
| 106 |
+
# A self-socket, really. :-)
|
| 107 |
+
self._ssock, self._csock = socket.socketpair()
|
| 108 |
+
self._ssock.setblocking(False)
|
| 109 |
+
self._csock.setblocking(False)
|
| 110 |
+
self._internal_fds += 1
|
| 111 |
+
self._add_reader(self._ssock.fileno(), self._read_from_self)
|
| 112 |
+
|
| 113 |
+
def _process_self_data(self, data):
|
| 114 |
+
pass
|
| 115 |
+
|
| 116 |
+
def _read_from_self(self):
|
| 117 |
+
while True:
|
| 118 |
+
try:
|
| 119 |
+
data = self._ssock.recv(4096)
|
| 120 |
+
if not data:
|
| 121 |
+
break
|
| 122 |
+
self._process_self_data(data)
|
| 123 |
+
except InterruptedError:
|
| 124 |
+
continue
|
| 125 |
+
except BlockingIOError:
|
| 126 |
+
break
|
| 127 |
+
|
| 128 |
+
def _write_to_self(self):
|
| 129 |
+
# This may be called from a different thread, possibly after
|
| 130 |
+
# _close_self_pipe() has been called or even while it is
|
| 131 |
+
# running. Guard for self._csock being None or closed. When
|
| 132 |
+
# a socket is closed, send() raises OSError (with errno set to
|
| 133 |
+
# EBADF, but let's not rely on the exact error code).
|
| 134 |
+
csock = self._csock
|
| 135 |
+
if csock is None:
|
| 136 |
+
return
|
| 137 |
+
|
| 138 |
+
try:
|
| 139 |
+
csock.send(b'\0')
|
| 140 |
+
except OSError:
|
| 141 |
+
if self._debug:
|
| 142 |
+
logger.debug("Fail to write a null byte into the "
|
| 143 |
+
"self-pipe socket",
|
| 144 |
+
exc_info=True)
|
| 145 |
+
|
| 146 |
+
def _start_serving(self, protocol_factory, sock,
|
| 147 |
+
sslcontext=None, server=None, backlog=100,
|
| 148 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT,
|
| 149 |
+
ssl_shutdown_timeout=constants.SSL_SHUTDOWN_TIMEOUT):
|
| 150 |
+
self._add_reader(sock.fileno(), self._accept_connection,
|
| 151 |
+
protocol_factory, sock, sslcontext, server, backlog,
|
| 152 |
+
ssl_handshake_timeout, ssl_shutdown_timeout)
|
| 153 |
+
|
| 154 |
+
def _accept_connection(
|
| 155 |
+
self, protocol_factory, sock,
|
| 156 |
+
sslcontext=None, server=None, backlog=100,
|
| 157 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT,
|
| 158 |
+
ssl_shutdown_timeout=constants.SSL_SHUTDOWN_TIMEOUT):
|
| 159 |
+
# This method is only called once for each event loop tick where the
|
| 160 |
+
# listening socket has triggered an EVENT_READ. There may be multiple
|
| 161 |
+
# connections waiting for an .accept() so it is called in a loop.
|
| 162 |
+
# See https://bugs.python.org/issue27906 for more details.
|
| 163 |
+
for _ in range(backlog):
|
| 164 |
+
try:
|
| 165 |
+
conn, addr = sock.accept()
|
| 166 |
+
if self._debug:
|
| 167 |
+
logger.debug("%r got a new connection from %r: %r",
|
| 168 |
+
server, addr, conn)
|
| 169 |
+
conn.setblocking(False)
|
| 170 |
+
except (BlockingIOError, InterruptedError, ConnectionAbortedError):
|
| 171 |
+
# Early exit because the socket accept buffer is empty.
|
| 172 |
+
return None
|
| 173 |
+
except OSError as exc:
|
| 174 |
+
# There's nowhere to send the error, so just log it.
|
| 175 |
+
if exc.errno in (errno.EMFILE, errno.ENFILE,
|
| 176 |
+
errno.ENOBUFS, errno.ENOMEM):
|
| 177 |
+
# Some platforms (e.g. Linux keep reporting the FD as
|
| 178 |
+
# ready, so we remove the read handler temporarily.
|
| 179 |
+
# We'll try again in a while.
|
| 180 |
+
self.call_exception_handler({
|
| 181 |
+
'message': 'socket.accept() out of system resource',
|
| 182 |
+
'exception': exc,
|
| 183 |
+
'socket': trsock.TransportSocket(sock),
|
| 184 |
+
})
|
| 185 |
+
self._remove_reader(sock.fileno())
|
| 186 |
+
self.call_later(constants.ACCEPT_RETRY_DELAY,
|
| 187 |
+
self._start_serving,
|
| 188 |
+
protocol_factory, sock, sslcontext, server,
|
| 189 |
+
backlog, ssl_handshake_timeout,
|
| 190 |
+
ssl_shutdown_timeout)
|
| 191 |
+
else:
|
| 192 |
+
raise # The event loop will catch, log and ignore it.
|
| 193 |
+
else:
|
| 194 |
+
extra = {'peername': addr}
|
| 195 |
+
accept = self._accept_connection2(
|
| 196 |
+
protocol_factory, conn, extra, sslcontext, server,
|
| 197 |
+
ssl_handshake_timeout, ssl_shutdown_timeout)
|
| 198 |
+
self.create_task(accept)
|
| 199 |
+
|
| 200 |
+
async def _accept_connection2(
|
| 201 |
+
self, protocol_factory, conn, extra,
|
| 202 |
+
sslcontext=None, server=None,
|
| 203 |
+
ssl_handshake_timeout=constants.SSL_HANDSHAKE_TIMEOUT,
|
| 204 |
+
ssl_shutdown_timeout=constants.SSL_SHUTDOWN_TIMEOUT):
|
| 205 |
+
protocol = None
|
| 206 |
+
transport = None
|
| 207 |
+
try:
|
| 208 |
+
protocol = protocol_factory()
|
| 209 |
+
waiter = self.create_future()
|
| 210 |
+
if sslcontext:
|
| 211 |
+
transport = self._make_ssl_transport(
|
| 212 |
+
conn, protocol, sslcontext, waiter=waiter,
|
| 213 |
+
server_side=True, extra=extra, server=server,
|
| 214 |
+
ssl_handshake_timeout=ssl_handshake_timeout,
|
| 215 |
+
ssl_shutdown_timeout=ssl_shutdown_timeout)
|
| 216 |
+
else:
|
| 217 |
+
transport = self._make_socket_transport(
|
| 218 |
+
conn, protocol, waiter=waiter, extra=extra,
|
| 219 |
+
server=server)
|
| 220 |
+
|
| 221 |
+
try:
|
| 222 |
+
await waiter
|
| 223 |
+
except BaseException:
|
| 224 |
+
transport.close()
|
| 225 |
+
# gh-109534: When an exception is raised by the SSLProtocol object the
|
| 226 |
+
# exception set in this future can keep the protocol object alive and
|
| 227 |
+
# cause a reference cycle.
|
| 228 |
+
waiter = None
|
| 229 |
+
raise
|
| 230 |
+
# It's now up to the protocol to handle the connection.
|
| 231 |
+
|
| 232 |
+
except (SystemExit, KeyboardInterrupt):
|
| 233 |
+
raise
|
| 234 |
+
except BaseException as exc:
|
| 235 |
+
if self._debug:
|
| 236 |
+
context = {
|
| 237 |
+
'message':
|
| 238 |
+
'Error on transport creation for incoming connection',
|
| 239 |
+
'exception': exc,
|
| 240 |
+
}
|
| 241 |
+
if protocol is not None:
|
| 242 |
+
context['protocol'] = protocol
|
| 243 |
+
if transport is not None:
|
| 244 |
+
context['transport'] = transport
|
| 245 |
+
self.call_exception_handler(context)
|
| 246 |
+
|
| 247 |
+
def _ensure_fd_no_transport(self, fd):
|
| 248 |
+
fileno = fd
|
| 249 |
+
if not isinstance(fileno, int):
|
| 250 |
+
try:
|
| 251 |
+
fileno = int(fileno.fileno())
|
| 252 |
+
except (AttributeError, TypeError, ValueError):
|
| 253 |
+
# This code matches selectors._fileobj_to_fd function.
|
| 254 |
+
raise ValueError(f"Invalid file object: {fd!r}") from None
|
| 255 |
+
try:
|
| 256 |
+
transport = self._transports[fileno]
|
| 257 |
+
except KeyError:
|
| 258 |
+
pass
|
| 259 |
+
else:
|
| 260 |
+
if not transport.is_closing():
|
| 261 |
+
raise RuntimeError(
|
| 262 |
+
f'File descriptor {fd!r} is used by transport '
|
| 263 |
+
f'{transport!r}')
|
| 264 |
+
|
| 265 |
+
def _add_reader(self, fd, callback, *args):
|
| 266 |
+
self._check_closed()
|
| 267 |
+
handle = events.Handle(callback, args, self, None)
|
| 268 |
+
try:
|
| 269 |
+
key = self._selector.get_key(fd)
|
| 270 |
+
except KeyError:
|
| 271 |
+
self._selector.register(fd, selectors.EVENT_READ,
|
| 272 |
+
(handle, None))
|
| 273 |
+
else:
|
| 274 |
+
mask, (reader, writer) = key.events, key.data
|
| 275 |
+
self._selector.modify(fd, mask | selectors.EVENT_READ,
|
| 276 |
+
(handle, writer))
|
| 277 |
+
if reader is not None:
|
| 278 |
+
reader.cancel()
|
| 279 |
+
return handle
|
| 280 |
+
|
| 281 |
+
def _remove_reader(self, fd):
|
| 282 |
+
if self.is_closed():
|
| 283 |
+
return False
|
| 284 |
+
try:
|
| 285 |
+
key = self._selector.get_key(fd)
|
| 286 |
+
except KeyError:
|
| 287 |
+
return False
|
| 288 |
+
else:
|
| 289 |
+
mask, (reader, writer) = key.events, key.data
|
| 290 |
+
mask &= ~selectors.EVENT_READ
|
| 291 |
+
if not mask:
|
| 292 |
+
self._selector.unregister(fd)
|
| 293 |
+
else:
|
| 294 |
+
self._selector.modify(fd, mask, (None, writer))
|
| 295 |
+
|
| 296 |
+
if reader is not None:
|
| 297 |
+
reader.cancel()
|
| 298 |
+
return True
|
| 299 |
+
else:
|
| 300 |
+
return False
|
| 301 |
+
|
| 302 |
+
def _add_writer(self, fd, callback, *args):
|
| 303 |
+
self._check_closed()
|
| 304 |
+
handle = events.Handle(callback, args, self, None)
|
| 305 |
+
try:
|
| 306 |
+
key = self._selector.get_key(fd)
|
| 307 |
+
except KeyError:
|
| 308 |
+
self._selector.register(fd, selectors.EVENT_WRITE,
|
| 309 |
+
(None, handle))
|
| 310 |
+
else:
|
| 311 |
+
mask, (reader, writer) = key.events, key.data
|
| 312 |
+
self._selector.modify(fd, mask | selectors.EVENT_WRITE,
|
| 313 |
+
(reader, handle))
|
| 314 |
+
if writer is not None:
|
| 315 |
+
writer.cancel()
|
| 316 |
+
return handle
|
| 317 |
+
|
| 318 |
+
def _remove_writer(self, fd):
|
| 319 |
+
"""Remove a writer callback."""
|
| 320 |
+
if self.is_closed():
|
| 321 |
+
return False
|
| 322 |
+
try:
|
| 323 |
+
key = self._selector.get_key(fd)
|
| 324 |
+
except KeyError:
|
| 325 |
+
return False
|
| 326 |
+
else:
|
| 327 |
+
mask, (reader, writer) = key.events, key.data
|
| 328 |
+
# Remove both writer and connector.
|
| 329 |
+
mask &= ~selectors.EVENT_WRITE
|
| 330 |
+
if not mask:
|
| 331 |
+
self._selector.unregister(fd)
|
| 332 |
+
else:
|
| 333 |
+
self._selector.modify(fd, mask, (reader, None))
|
| 334 |
+
|
| 335 |
+
if writer is not None:
|
| 336 |
+
writer.cancel()
|
| 337 |
+
return True
|
| 338 |
+
else:
|
| 339 |
+
return False
|
| 340 |
+
|
| 341 |
+
def add_reader(self, fd, callback, *args):
|
| 342 |
+
"""Add a reader callback."""
|
| 343 |
+
self._ensure_fd_no_transport(fd)
|
| 344 |
+
self._add_reader(fd, callback, *args)
|
| 345 |
+
|
| 346 |
+
def remove_reader(self, fd):
|
| 347 |
+
"""Remove a reader callback."""
|
| 348 |
+
self._ensure_fd_no_transport(fd)
|
| 349 |
+
return self._remove_reader(fd)
|
| 350 |
+
|
| 351 |
+
def add_writer(self, fd, callback, *args):
|
| 352 |
+
"""Add a writer callback.."""
|
| 353 |
+
self._ensure_fd_no_transport(fd)
|
| 354 |
+
self._add_writer(fd, callback, *args)
|
| 355 |
+
|
| 356 |
+
def remove_writer(self, fd):
|
| 357 |
+
"""Remove a writer callback."""
|
| 358 |
+
self._ensure_fd_no_transport(fd)
|
| 359 |
+
return self._remove_writer(fd)
|
| 360 |
+
|
| 361 |
+
async def sock_recv(self, sock, n):
|
| 362 |
+
"""Receive data from the socket.
|
| 363 |
+
|
| 364 |
+
The return value is a bytes object representing the data received.
|
| 365 |
+
The maximum amount of data to be received at once is specified by
|
| 366 |
+
nbytes.
|
| 367 |
+
"""
|
| 368 |
+
base_events._check_ssl_socket(sock)
|
| 369 |
+
if self._debug and sock.gettimeout() != 0:
|
| 370 |
+
raise ValueError("the socket must be non-blocking")
|
| 371 |
+
try:
|
| 372 |
+
return sock.recv(n)
|
| 373 |
+
except (BlockingIOError, InterruptedError):
|
| 374 |
+
pass
|
| 375 |
+
fut = self.create_future()
|
| 376 |
+
fd = sock.fileno()
|
| 377 |
+
self._ensure_fd_no_transport(fd)
|
| 378 |
+
handle = self._add_reader(fd, self._sock_recv, fut, sock, n)
|
| 379 |
+
fut.add_done_callback(
|
| 380 |
+
functools.partial(self._sock_read_done, fd, handle=handle))
|
| 381 |
+
return await fut
|
| 382 |
+
|
| 383 |
+
def _sock_read_done(self, fd, fut, handle=None):
|
| 384 |
+
if handle is None or not handle.cancelled():
|
| 385 |
+
self.remove_reader(fd)
|
| 386 |
+
|
| 387 |
+
def _sock_recv(self, fut, sock, n):
|
| 388 |
+
# _sock_recv() can add itself as an I/O callback if the operation can't
|
| 389 |
+
# be done immediately. Don't use it directly, call sock_recv().
|
| 390 |
+
if fut.done():
|
| 391 |
+
return
|
| 392 |
+
try:
|
| 393 |
+
data = sock.recv(n)
|
| 394 |
+
except (BlockingIOError, InterruptedError):
|
| 395 |
+
return # try again next time
|
| 396 |
+
except (SystemExit, KeyboardInterrupt):
|
| 397 |
+
raise
|
| 398 |
+
except BaseException as exc:
|
| 399 |
+
fut.set_exception(exc)
|
| 400 |
+
else:
|
| 401 |
+
fut.set_result(data)
|
| 402 |
+
|
| 403 |
+
async def sock_recv_into(self, sock, buf):
|
| 404 |
+
"""Receive data from the socket.
|
| 405 |
+
|
| 406 |
+
The received data is written into *buf* (a writable buffer).
|
| 407 |
+
The return value is the number of bytes written.
|
| 408 |
+
"""
|
| 409 |
+
base_events._check_ssl_socket(sock)
|
| 410 |
+
if self._debug and sock.gettimeout() != 0:
|
| 411 |
+
raise ValueError("the socket must be non-blocking")
|
| 412 |
+
try:
|
| 413 |
+
return sock.recv_into(buf)
|
| 414 |
+
except (BlockingIOError, InterruptedError):
|
| 415 |
+
pass
|
| 416 |
+
fut = self.create_future()
|
| 417 |
+
fd = sock.fileno()
|
| 418 |
+
self._ensure_fd_no_transport(fd)
|
| 419 |
+
handle = self._add_reader(fd, self._sock_recv_into, fut, sock, buf)
|
| 420 |
+
fut.add_done_callback(
|
| 421 |
+
functools.partial(self._sock_read_done, fd, handle=handle))
|
| 422 |
+
return await fut
|
| 423 |
+
|
| 424 |
+
def _sock_recv_into(self, fut, sock, buf):
|
| 425 |
+
# _sock_recv_into() can add itself as an I/O callback if the operation
|
| 426 |
+
# can't be done immediately. Don't use it directly, call
|
| 427 |
+
# sock_recv_into().
|
| 428 |
+
if fut.done():
|
| 429 |
+
return
|
| 430 |
+
try:
|
| 431 |
+
nbytes = sock.recv_into(buf)
|
| 432 |
+
except (BlockingIOError, InterruptedError):
|
| 433 |
+
return # try again next time
|
| 434 |
+
except (SystemExit, KeyboardInterrupt):
|
| 435 |
+
raise
|
| 436 |
+
except BaseException as exc:
|
| 437 |
+
fut.set_exception(exc)
|
| 438 |
+
else:
|
| 439 |
+
fut.set_result(nbytes)
|
| 440 |
+
|
| 441 |
+
async def sock_recvfrom(self, sock, bufsize):
|
| 442 |
+
"""Receive a datagram from a datagram socket.
|
| 443 |
+
|
| 444 |
+
The return value is a tuple of (bytes, address) representing the
|
| 445 |
+
datagram received and the address it came from.
|
| 446 |
+
The maximum amount of data to be received at once is specified by
|
| 447 |
+
nbytes.
|
| 448 |
+
"""
|
| 449 |
+
base_events._check_ssl_socket(sock)
|
| 450 |
+
if self._debug and sock.gettimeout() != 0:
|
| 451 |
+
raise ValueError("the socket must be non-blocking")
|
| 452 |
+
try:
|
| 453 |
+
return sock.recvfrom(bufsize)
|
| 454 |
+
except (BlockingIOError, InterruptedError):
|
| 455 |
+
pass
|
| 456 |
+
fut = self.create_future()
|
| 457 |
+
fd = sock.fileno()
|
| 458 |
+
self._ensure_fd_no_transport(fd)
|
| 459 |
+
handle = self._add_reader(fd, self._sock_recvfrom, fut, sock, bufsize)
|
| 460 |
+
fut.add_done_callback(
|
| 461 |
+
functools.partial(self._sock_read_done, fd, handle=handle))
|
| 462 |
+
return await fut
|
| 463 |
+
|
| 464 |
+
def _sock_recvfrom(self, fut, sock, bufsize):
|
| 465 |
+
# _sock_recvfrom() can add itself as an I/O callback if the operation
|
| 466 |
+
# can't be done immediately. Don't use it directly, call
|
| 467 |
+
# sock_recvfrom().
|
| 468 |
+
if fut.done():
|
| 469 |
+
return
|
| 470 |
+
try:
|
| 471 |
+
result = sock.recvfrom(bufsize)
|
| 472 |
+
except (BlockingIOError, InterruptedError):
|
| 473 |
+
return # try again next time
|
| 474 |
+
except (SystemExit, KeyboardInterrupt):
|
| 475 |
+
raise
|
| 476 |
+
except BaseException as exc:
|
| 477 |
+
fut.set_exception(exc)
|
| 478 |
+
else:
|
| 479 |
+
fut.set_result(result)
|
| 480 |
+
|
| 481 |
+
async def sock_recvfrom_into(self, sock, buf, nbytes=0):
|
| 482 |
+
"""Receive data from the socket.
|
| 483 |
+
|
| 484 |
+
The received data is written into *buf* (a writable buffer).
|
| 485 |
+
The return value is a tuple of (number of bytes written, address).
|
| 486 |
+
"""
|
| 487 |
+
base_events._check_ssl_socket(sock)
|
| 488 |
+
if self._debug and sock.gettimeout() != 0:
|
| 489 |
+
raise ValueError("the socket must be non-blocking")
|
| 490 |
+
if not nbytes:
|
| 491 |
+
nbytes = len(buf)
|
| 492 |
+
|
| 493 |
+
try:
|
| 494 |
+
return sock.recvfrom_into(buf, nbytes)
|
| 495 |
+
except (BlockingIOError, InterruptedError):
|
| 496 |
+
pass
|
| 497 |
+
fut = self.create_future()
|
| 498 |
+
fd = sock.fileno()
|
| 499 |
+
self._ensure_fd_no_transport(fd)
|
| 500 |
+
handle = self._add_reader(fd, self._sock_recvfrom_into, fut, sock, buf,
|
| 501 |
+
nbytes)
|
| 502 |
+
fut.add_done_callback(
|
| 503 |
+
functools.partial(self._sock_read_done, fd, handle=handle))
|
| 504 |
+
return await fut
|
| 505 |
+
|
| 506 |
+
def _sock_recvfrom_into(self, fut, sock, buf, bufsize):
|
| 507 |
+
# _sock_recv_into() can add itself as an I/O callback if the operation
|
| 508 |
+
# can't be done immediately. Don't use it directly, call
|
| 509 |
+
# sock_recv_into().
|
| 510 |
+
if fut.done():
|
| 511 |
+
return
|
| 512 |
+
try:
|
| 513 |
+
result = sock.recvfrom_into(buf, bufsize)
|
| 514 |
+
except (BlockingIOError, InterruptedError):
|
| 515 |
+
return # try again next time
|
| 516 |
+
except (SystemExit, KeyboardInterrupt):
|
| 517 |
+
raise
|
| 518 |
+
except BaseException as exc:
|
| 519 |
+
fut.set_exception(exc)
|
| 520 |
+
else:
|
| 521 |
+
fut.set_result(result)
|
| 522 |
+
|
| 523 |
+
async def sock_sendall(self, sock, data):
|
| 524 |
+
"""Send data to the socket.
|
| 525 |
+
|
| 526 |
+
The socket must be connected to a remote socket. This method continues
|
| 527 |
+
to send data from data until either all data has been sent or an
|
| 528 |
+
error occurs. None is returned on success. On error, an exception is
|
| 529 |
+
raised, and there is no way to determine how much data, if any, was
|
| 530 |
+
successfully processed by the receiving end of the connection.
|
| 531 |
+
"""
|
| 532 |
+
base_events._check_ssl_socket(sock)
|
| 533 |
+
if self._debug and sock.gettimeout() != 0:
|
| 534 |
+
raise ValueError("the socket must be non-blocking")
|
| 535 |
+
try:
|
| 536 |
+
n = sock.send(data)
|
| 537 |
+
except (BlockingIOError, InterruptedError):
|
| 538 |
+
n = 0
|
| 539 |
+
|
| 540 |
+
if n == len(data):
|
| 541 |
+
# all data sent
|
| 542 |
+
return
|
| 543 |
+
|
| 544 |
+
fut = self.create_future()
|
| 545 |
+
fd = sock.fileno()
|
| 546 |
+
self._ensure_fd_no_transport(fd)
|
| 547 |
+
# use a trick with a list in closure to store a mutable state
|
| 548 |
+
handle = self._add_writer(fd, self._sock_sendall, fut, sock,
|
| 549 |
+
memoryview(data), [n])
|
| 550 |
+
fut.add_done_callback(
|
| 551 |
+
functools.partial(self._sock_write_done, fd, handle=handle))
|
| 552 |
+
return await fut
|
| 553 |
+
|
| 554 |
+
def _sock_sendall(self, fut, sock, view, pos):
|
| 555 |
+
if fut.done():
|
| 556 |
+
# Future cancellation can be scheduled on previous loop iteration
|
| 557 |
+
return
|
| 558 |
+
start = pos[0]
|
| 559 |
+
try:
|
| 560 |
+
n = sock.send(view[start:])
|
| 561 |
+
except (BlockingIOError, InterruptedError):
|
| 562 |
+
return
|
| 563 |
+
except (SystemExit, KeyboardInterrupt):
|
| 564 |
+
raise
|
| 565 |
+
except BaseException as exc:
|
| 566 |
+
fut.set_exception(exc)
|
| 567 |
+
return
|
| 568 |
+
|
| 569 |
+
start += n
|
| 570 |
+
|
| 571 |
+
if start == len(view):
|
| 572 |
+
fut.set_result(None)
|
| 573 |
+
else:
|
| 574 |
+
pos[0] = start
|
| 575 |
+
|
| 576 |
+
async def sock_sendto(self, sock, data, address):
|
| 577 |
+
"""Send data to the socket.
|
| 578 |
+
|
| 579 |
+
The socket must be connected to a remote socket. This method continues
|
| 580 |
+
to send data from data until either all data has been sent or an
|
| 581 |
+
error occurs. None is returned on success. On error, an exception is
|
| 582 |
+
raised, and there is no way to determine how much data, if any, was
|
| 583 |
+
successfully processed by the receiving end of the connection.
|
| 584 |
+
"""
|
| 585 |
+
base_events._check_ssl_socket(sock)
|
| 586 |
+
if self._debug and sock.gettimeout() != 0:
|
| 587 |
+
raise ValueError("the socket must be non-blocking")
|
| 588 |
+
try:
|
| 589 |
+
return sock.sendto(data, address)
|
| 590 |
+
except (BlockingIOError, InterruptedError):
|
| 591 |
+
pass
|
| 592 |
+
|
| 593 |
+
fut = self.create_future()
|
| 594 |
+
fd = sock.fileno()
|
| 595 |
+
self._ensure_fd_no_transport(fd)
|
| 596 |
+
# use a trick with a list in closure to store a mutable state
|
| 597 |
+
handle = self._add_writer(fd, self._sock_sendto, fut, sock, data,
|
| 598 |
+
address)
|
| 599 |
+
fut.add_done_callback(
|
| 600 |
+
functools.partial(self._sock_write_done, fd, handle=handle))
|
| 601 |
+
return await fut
|
| 602 |
+
|
| 603 |
+
def _sock_sendto(self, fut, sock, data, address):
|
| 604 |
+
if fut.done():
|
| 605 |
+
# Future cancellation can be scheduled on previous loop iteration
|
| 606 |
+
return
|
| 607 |
+
try:
|
| 608 |
+
n = sock.sendto(data, 0, address)
|
| 609 |
+
except (BlockingIOError, InterruptedError):
|
| 610 |
+
return
|
| 611 |
+
except (SystemExit, KeyboardInterrupt):
|
| 612 |
+
raise
|
| 613 |
+
except BaseException as exc:
|
| 614 |
+
fut.set_exception(exc)
|
| 615 |
+
else:
|
| 616 |
+
fut.set_result(n)
|
| 617 |
+
|
| 618 |
+
async def sock_connect(self, sock, address):
|
| 619 |
+
"""Connect to a remote socket at address.
|
| 620 |
+
|
| 621 |
+
This method is a coroutine.
|
| 622 |
+
"""
|
| 623 |
+
base_events._check_ssl_socket(sock)
|
| 624 |
+
if self._debug and sock.gettimeout() != 0:
|
| 625 |
+
raise ValueError("the socket must be non-blocking")
|
| 626 |
+
|
| 627 |
+
if sock.family == socket.AF_INET or (
|
| 628 |
+
base_events._HAS_IPv6 and sock.family == socket.AF_INET6):
|
| 629 |
+
resolved = await self._ensure_resolved(
|
| 630 |
+
address, family=sock.family, type=sock.type, proto=sock.proto,
|
| 631 |
+
loop=self,
|
| 632 |
+
)
|
| 633 |
+
_, _, _, _, address = resolved[0]
|
| 634 |
+
|
| 635 |
+
fut = self.create_future()
|
| 636 |
+
self._sock_connect(fut, sock, address)
|
| 637 |
+
try:
|
| 638 |
+
return await fut
|
| 639 |
+
finally:
|
| 640 |
+
# Needed to break cycles when an exception occurs.
|
| 641 |
+
fut = None
|
| 642 |
+
|
| 643 |
+
def _sock_connect(self, fut, sock, address):
|
| 644 |
+
fd = sock.fileno()
|
| 645 |
+
try:
|
| 646 |
+
sock.connect(address)
|
| 647 |
+
except (BlockingIOError, InterruptedError):
|
| 648 |
+
# Issue #23618: When the C function connect() fails with EINTR, the
|
| 649 |
+
# connection runs in background. We have to wait until the socket
|
| 650 |
+
# becomes writable to be notified when the connection succeed or
|
| 651 |
+
# fails.
|
| 652 |
+
self._ensure_fd_no_transport(fd)
|
| 653 |
+
handle = self._add_writer(
|
| 654 |
+
fd, self._sock_connect_cb, fut, sock, address)
|
| 655 |
+
fut.add_done_callback(
|
| 656 |
+
functools.partial(self._sock_write_done, fd, handle=handle))
|
| 657 |
+
except (SystemExit, KeyboardInterrupt):
|
| 658 |
+
raise
|
| 659 |
+
except BaseException as exc:
|
| 660 |
+
fut.set_exception(exc)
|
| 661 |
+
else:
|
| 662 |
+
fut.set_result(None)
|
| 663 |
+
finally:
|
| 664 |
+
fut = None
|
| 665 |
+
|
| 666 |
+
def _sock_write_done(self, fd, fut, handle=None):
|
| 667 |
+
if handle is None or not handle.cancelled():
|
| 668 |
+
self.remove_writer(fd)
|
| 669 |
+
|
| 670 |
+
def _sock_connect_cb(self, fut, sock, address):
|
| 671 |
+
if fut.done():
|
| 672 |
+
return
|
| 673 |
+
|
| 674 |
+
try:
|
| 675 |
+
err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
|
| 676 |
+
if err != 0:
|
| 677 |
+
# Jump to any except clause below.
|
| 678 |
+
raise OSError(err, f'Connect call failed {address}')
|
| 679 |
+
except (BlockingIOError, InterruptedError):
|
| 680 |
+
# socket is still registered, the callback will be retried later
|
| 681 |
+
pass
|
| 682 |
+
except (SystemExit, KeyboardInterrupt):
|
| 683 |
+
raise
|
| 684 |
+
except BaseException as exc:
|
| 685 |
+
fut.set_exception(exc)
|
| 686 |
+
else:
|
| 687 |
+
fut.set_result(None)
|
| 688 |
+
finally:
|
| 689 |
+
fut = None
|
| 690 |
+
|
| 691 |
+
async def sock_accept(self, sock):
|
| 692 |
+
"""Accept a connection.
|
| 693 |
+
|
| 694 |
+
The socket must be bound to an address and listening for connections.
|
| 695 |
+
The return value is a pair (conn, address) where conn is a new socket
|
| 696 |
+
object usable to send and receive data on the connection, and address
|
| 697 |
+
is the address bound to the socket on the other end of the connection.
|
| 698 |
+
"""
|
| 699 |
+
base_events._check_ssl_socket(sock)
|
| 700 |
+
if self._debug and sock.gettimeout() != 0:
|
| 701 |
+
raise ValueError("the socket must be non-blocking")
|
| 702 |
+
fut = self.create_future()
|
| 703 |
+
self._sock_accept(fut, sock)
|
| 704 |
+
return await fut
|
| 705 |
+
|
| 706 |
+
def _sock_accept(self, fut, sock):
|
| 707 |
+
fd = sock.fileno()
|
| 708 |
+
try:
|
| 709 |
+
conn, address = sock.accept()
|
| 710 |
+
conn.setblocking(False)
|
| 711 |
+
except (BlockingIOError, InterruptedError):
|
| 712 |
+
self._ensure_fd_no_transport(fd)
|
| 713 |
+
handle = self._add_reader(fd, self._sock_accept, fut, sock)
|
| 714 |
+
fut.add_done_callback(
|
| 715 |
+
functools.partial(self._sock_read_done, fd, handle=handle))
|
| 716 |
+
except (SystemExit, KeyboardInterrupt):
|
| 717 |
+
raise
|
| 718 |
+
except BaseException as exc:
|
| 719 |
+
fut.set_exception(exc)
|
| 720 |
+
else:
|
| 721 |
+
fut.set_result((conn, address))
|
| 722 |
+
|
| 723 |
+
async def _sendfile_native(self, transp, file, offset, count):
|
| 724 |
+
del self._transports[transp._sock_fd]
|
| 725 |
+
resume_reading = transp.is_reading()
|
| 726 |
+
transp.pause_reading()
|
| 727 |
+
await transp._make_empty_waiter()
|
| 728 |
+
try:
|
| 729 |
+
return await self.sock_sendfile(transp._sock, file, offset, count,
|
| 730 |
+
fallback=False)
|
| 731 |
+
finally:
|
| 732 |
+
transp._reset_empty_waiter()
|
| 733 |
+
if resume_reading:
|
| 734 |
+
transp.resume_reading()
|
| 735 |
+
self._transports[transp._sock_fd] = transp
|
| 736 |
+
|
| 737 |
+
def _process_events(self, event_list):
|
| 738 |
+
for key, mask in event_list:
|
| 739 |
+
fileobj, (reader, writer) = key.fileobj, key.data
|
| 740 |
+
if mask & selectors.EVENT_READ and reader is not None:
|
| 741 |
+
if reader._cancelled:
|
| 742 |
+
self._remove_reader(fileobj)
|
| 743 |
+
else:
|
| 744 |
+
self._add_callback(reader)
|
| 745 |
+
if mask & selectors.EVENT_WRITE and writer is not None:
|
| 746 |
+
if writer._cancelled:
|
| 747 |
+
self._remove_writer(fileobj)
|
| 748 |
+
else:
|
| 749 |
+
self._add_callback(writer)
|
| 750 |
+
|
| 751 |
+
def _stop_serving(self, sock):
|
| 752 |
+
self._remove_reader(sock.fileno())
|
| 753 |
+
sock.close()
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
class _SelectorTransport(transports._FlowControlMixin,
|
| 757 |
+
transports.Transport):
|
| 758 |
+
|
| 759 |
+
max_size = 256 * 1024 # Buffer size passed to recv().
|
| 760 |
+
|
| 761 |
+
_buffer_factory = bytearray # Constructs initial value for self._buffer.
|
| 762 |
+
|
| 763 |
+
# Attribute used in the destructor: it must be set even if the constructor
|
| 764 |
+
# is not called (see _SelectorSslTransport which may start by raising an
|
| 765 |
+
# exception)
|
| 766 |
+
_sock = None
|
| 767 |
+
|
| 768 |
+
def __init__(self, loop, sock, protocol, extra=None, server=None):
|
| 769 |
+
super().__init__(extra, loop)
|
| 770 |
+
self._extra['socket'] = trsock.TransportSocket(sock)
|
| 771 |
+
try:
|
| 772 |
+
self._extra['sockname'] = sock.getsockname()
|
| 773 |
+
except OSError:
|
| 774 |
+
self._extra['sockname'] = None
|
| 775 |
+
if 'peername' not in self._extra:
|
| 776 |
+
try:
|
| 777 |
+
self._extra['peername'] = sock.getpeername()
|
| 778 |
+
except socket.error:
|
| 779 |
+
self._extra['peername'] = None
|
| 780 |
+
self._sock = sock
|
| 781 |
+
self._sock_fd = sock.fileno()
|
| 782 |
+
|
| 783 |
+
self._protocol_connected = False
|
| 784 |
+
self.set_protocol(protocol)
|
| 785 |
+
|
| 786 |
+
self._server = server
|
| 787 |
+
self._buffer = self._buffer_factory()
|
| 788 |
+
self._conn_lost = 0 # Set when call to connection_lost scheduled.
|
| 789 |
+
self._closing = False # Set when close() called.
|
| 790 |
+
self._paused = False # Set when pause_reading() called
|
| 791 |
+
|
| 792 |
+
if self._server is not None:
|
| 793 |
+
self._server._attach()
|
| 794 |
+
loop._transports[self._sock_fd] = self
|
| 795 |
+
|
| 796 |
+
def __repr__(self):
|
| 797 |
+
info = [self.__class__.__name__]
|
| 798 |
+
if self._sock is None:
|
| 799 |
+
info.append('closed')
|
| 800 |
+
elif self._closing:
|
| 801 |
+
info.append('closing')
|
| 802 |
+
info.append(f'fd={self._sock_fd}')
|
| 803 |
+
# test if the transport was closed
|
| 804 |
+
if self._loop is not None and not self._loop.is_closed():
|
| 805 |
+
polling = _test_selector_event(self._loop._selector,
|
| 806 |
+
self._sock_fd, selectors.EVENT_READ)
|
| 807 |
+
if polling:
|
| 808 |
+
info.append('read=polling')
|
| 809 |
+
else:
|
| 810 |
+
info.append('read=idle')
|
| 811 |
+
|
| 812 |
+
polling = _test_selector_event(self._loop._selector,
|
| 813 |
+
self._sock_fd,
|
| 814 |
+
selectors.EVENT_WRITE)
|
| 815 |
+
if polling:
|
| 816 |
+
state = 'polling'
|
| 817 |
+
else:
|
| 818 |
+
state = 'idle'
|
| 819 |
+
|
| 820 |
+
bufsize = self.get_write_buffer_size()
|
| 821 |
+
info.append(f'write=<{state}, bufsize={bufsize}>')
|
| 822 |
+
return '<{}>'.format(' '.join(info))
|
| 823 |
+
|
| 824 |
+
def abort(self):
|
| 825 |
+
self._force_close(None)
|
| 826 |
+
|
| 827 |
+
def set_protocol(self, protocol):
|
| 828 |
+
self._protocol = protocol
|
| 829 |
+
self._protocol_connected = True
|
| 830 |
+
|
| 831 |
+
def get_protocol(self):
|
| 832 |
+
return self._protocol
|
| 833 |
+
|
| 834 |
+
def is_closing(self):
|
| 835 |
+
return self._closing
|
| 836 |
+
|
| 837 |
+
def is_reading(self):
|
| 838 |
+
return not self.is_closing() and not self._paused
|
| 839 |
+
|
| 840 |
+
def pause_reading(self):
|
| 841 |
+
if not self.is_reading():
|
| 842 |
+
return
|
| 843 |
+
self._paused = True
|
| 844 |
+
self._loop._remove_reader(self._sock_fd)
|
| 845 |
+
if self._loop.get_debug():
|
| 846 |
+
logger.debug("%r pauses reading", self)
|
| 847 |
+
|
| 848 |
+
def resume_reading(self):
|
| 849 |
+
if self._closing or not self._paused:
|
| 850 |
+
return
|
| 851 |
+
self._paused = False
|
| 852 |
+
self._add_reader(self._sock_fd, self._read_ready)
|
| 853 |
+
if self._loop.get_debug():
|
| 854 |
+
logger.debug("%r resumes reading", self)
|
| 855 |
+
|
| 856 |
+
def close(self):
|
| 857 |
+
if self._closing:
|
| 858 |
+
return
|
| 859 |
+
self._closing = True
|
| 860 |
+
self._loop._remove_reader(self._sock_fd)
|
| 861 |
+
if not self._buffer:
|
| 862 |
+
self._conn_lost += 1
|
| 863 |
+
self._loop._remove_writer(self._sock_fd)
|
| 864 |
+
self._loop.call_soon(self._call_connection_lost, None)
|
| 865 |
+
|
| 866 |
+
def __del__(self, _warn=warnings.warn):
|
| 867 |
+
if self._sock is not None:
|
| 868 |
+
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
|
| 869 |
+
self._sock.close()
|
| 870 |
+
|
| 871 |
+
def _fatal_error(self, exc, message='Fatal error on transport'):
|
| 872 |
+
# Should be called from exception handler only.
|
| 873 |
+
if isinstance(exc, OSError):
|
| 874 |
+
if self._loop.get_debug():
|
| 875 |
+
logger.debug("%r: %s", self, message, exc_info=True)
|
| 876 |
+
else:
|
| 877 |
+
self._loop.call_exception_handler({
|
| 878 |
+
'message': message,
|
| 879 |
+
'exception': exc,
|
| 880 |
+
'transport': self,
|
| 881 |
+
'protocol': self._protocol,
|
| 882 |
+
})
|
| 883 |
+
self._force_close(exc)
|
| 884 |
+
|
| 885 |
+
def _force_close(self, exc):
|
| 886 |
+
if self._conn_lost:
|
| 887 |
+
return
|
| 888 |
+
if self._buffer:
|
| 889 |
+
self._buffer.clear()
|
| 890 |
+
self._loop._remove_writer(self._sock_fd)
|
| 891 |
+
if not self._closing:
|
| 892 |
+
self._closing = True
|
| 893 |
+
self._loop._remove_reader(self._sock_fd)
|
| 894 |
+
self._conn_lost += 1
|
| 895 |
+
self._loop.call_soon(self._call_connection_lost, exc)
|
| 896 |
+
|
| 897 |
+
def _call_connection_lost(self, exc):
|
| 898 |
+
try:
|
| 899 |
+
if self._protocol_connected:
|
| 900 |
+
self._protocol.connection_lost(exc)
|
| 901 |
+
finally:
|
| 902 |
+
self._sock.close()
|
| 903 |
+
self._sock = None
|
| 904 |
+
self._protocol = None
|
| 905 |
+
self._loop = None
|
| 906 |
+
server = self._server
|
| 907 |
+
if server is not None:
|
| 908 |
+
server._detach()
|
| 909 |
+
self._server = None
|
| 910 |
+
|
| 911 |
+
def get_write_buffer_size(self):
|
| 912 |
+
return len(self._buffer)
|
| 913 |
+
|
| 914 |
+
def _add_reader(self, fd, callback, *args):
|
| 915 |
+
if not self.is_reading():
|
| 916 |
+
return
|
| 917 |
+
self._loop._add_reader(fd, callback, *args)
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
class _SelectorSocketTransport(_SelectorTransport):
|
| 921 |
+
|
| 922 |
+
_start_tls_compatible = True
|
| 923 |
+
_sendfile_compatible = constants._SendfileMode.TRY_NATIVE
|
| 924 |
+
|
| 925 |
+
def __init__(self, loop, sock, protocol, waiter=None,
|
| 926 |
+
extra=None, server=None):
|
| 927 |
+
|
| 928 |
+
self._read_ready_cb = None
|
| 929 |
+
super().__init__(loop, sock, protocol, extra, server)
|
| 930 |
+
self._eof = False
|
| 931 |
+
self._empty_waiter = None
|
| 932 |
+
|
| 933 |
+
# Disable the Nagle algorithm -- small writes will be
|
| 934 |
+
# sent without waiting for the TCP ACK. This generally
|
| 935 |
+
# decreases the latency (in some cases significantly.)
|
| 936 |
+
base_events._set_nodelay(self._sock)
|
| 937 |
+
|
| 938 |
+
self._loop.call_soon(self._protocol.connection_made, self)
|
| 939 |
+
# only start reading when connection_made() has been called
|
| 940 |
+
self._loop.call_soon(self._add_reader,
|
| 941 |
+
self._sock_fd, self._read_ready)
|
| 942 |
+
if waiter is not None:
|
| 943 |
+
# only wake up the waiter when connection_made() has been called
|
| 944 |
+
self._loop.call_soon(futures._set_result_unless_cancelled,
|
| 945 |
+
waiter, None)
|
| 946 |
+
|
| 947 |
+
def set_protocol(self, protocol):
|
| 948 |
+
if isinstance(protocol, protocols.BufferedProtocol):
|
| 949 |
+
self._read_ready_cb = self._read_ready__get_buffer
|
| 950 |
+
else:
|
| 951 |
+
self._read_ready_cb = self._read_ready__data_received
|
| 952 |
+
|
| 953 |
+
super().set_protocol(protocol)
|
| 954 |
+
|
| 955 |
+
def _read_ready(self):
|
| 956 |
+
self._read_ready_cb()
|
| 957 |
+
|
| 958 |
+
def _read_ready__get_buffer(self):
|
| 959 |
+
if self._conn_lost:
|
| 960 |
+
return
|
| 961 |
+
|
| 962 |
+
try:
|
| 963 |
+
buf = self._protocol.get_buffer(-1)
|
| 964 |
+
if not len(buf):
|
| 965 |
+
raise RuntimeError('get_buffer() returned an empty buffer')
|
| 966 |
+
except (SystemExit, KeyboardInterrupt):
|
| 967 |
+
raise
|
| 968 |
+
except BaseException as exc:
|
| 969 |
+
self._fatal_error(
|
| 970 |
+
exc, 'Fatal error: protocol.get_buffer() call failed.')
|
| 971 |
+
return
|
| 972 |
+
|
| 973 |
+
try:
|
| 974 |
+
nbytes = self._sock.recv_into(buf)
|
| 975 |
+
except (BlockingIOError, InterruptedError):
|
| 976 |
+
return
|
| 977 |
+
except (SystemExit, KeyboardInterrupt):
|
| 978 |
+
raise
|
| 979 |
+
except BaseException as exc:
|
| 980 |
+
self._fatal_error(exc, 'Fatal read error on socket transport')
|
| 981 |
+
return
|
| 982 |
+
|
| 983 |
+
if not nbytes:
|
| 984 |
+
self._read_ready__on_eof()
|
| 985 |
+
return
|
| 986 |
+
|
| 987 |
+
try:
|
| 988 |
+
self._protocol.buffer_updated(nbytes)
|
| 989 |
+
except (SystemExit, KeyboardInterrupt):
|
| 990 |
+
raise
|
| 991 |
+
except BaseException as exc:
|
| 992 |
+
self._fatal_error(
|
| 993 |
+
exc, 'Fatal error: protocol.buffer_updated() call failed.')
|
| 994 |
+
|
| 995 |
+
def _read_ready__data_received(self):
|
| 996 |
+
if self._conn_lost:
|
| 997 |
+
return
|
| 998 |
+
try:
|
| 999 |
+
data = self._sock.recv(self.max_size)
|
| 1000 |
+
except (BlockingIOError, InterruptedError):
|
| 1001 |
+
return
|
| 1002 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1003 |
+
raise
|
| 1004 |
+
except BaseException as exc:
|
| 1005 |
+
self._fatal_error(exc, 'Fatal read error on socket transport')
|
| 1006 |
+
return
|
| 1007 |
+
|
| 1008 |
+
if not data:
|
| 1009 |
+
self._read_ready__on_eof()
|
| 1010 |
+
return
|
| 1011 |
+
|
| 1012 |
+
try:
|
| 1013 |
+
self._protocol.data_received(data)
|
| 1014 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1015 |
+
raise
|
| 1016 |
+
except BaseException as exc:
|
| 1017 |
+
self._fatal_error(
|
| 1018 |
+
exc, 'Fatal error: protocol.data_received() call failed.')
|
| 1019 |
+
|
| 1020 |
+
def _read_ready__on_eof(self):
|
| 1021 |
+
if self._loop.get_debug():
|
| 1022 |
+
logger.debug("%r received EOF", self)
|
| 1023 |
+
|
| 1024 |
+
try:
|
| 1025 |
+
keep_open = self._protocol.eof_received()
|
| 1026 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1027 |
+
raise
|
| 1028 |
+
except BaseException as exc:
|
| 1029 |
+
self._fatal_error(
|
| 1030 |
+
exc, 'Fatal error: protocol.eof_received() call failed.')
|
| 1031 |
+
return
|
| 1032 |
+
|
| 1033 |
+
if keep_open:
|
| 1034 |
+
# We're keeping the connection open so the
|
| 1035 |
+
# protocol can write more, but we still can't
|
| 1036 |
+
# receive more, so remove the reader callback.
|
| 1037 |
+
self._loop._remove_reader(self._sock_fd)
|
| 1038 |
+
else:
|
| 1039 |
+
self.close()
|
| 1040 |
+
|
| 1041 |
+
def write(self, data):
|
| 1042 |
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
| 1043 |
+
raise TypeError(f'data argument must be a bytes-like object, '
|
| 1044 |
+
f'not {type(data).__name__!r}')
|
| 1045 |
+
if self._eof:
|
| 1046 |
+
raise RuntimeError('Cannot call write() after write_eof()')
|
| 1047 |
+
if self._empty_waiter is not None:
|
| 1048 |
+
raise RuntimeError('unable to write; sendfile is in progress')
|
| 1049 |
+
if not data:
|
| 1050 |
+
return
|
| 1051 |
+
|
| 1052 |
+
if self._conn_lost:
|
| 1053 |
+
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
|
| 1054 |
+
logger.warning('socket.send() raised exception.')
|
| 1055 |
+
self._conn_lost += 1
|
| 1056 |
+
return
|
| 1057 |
+
|
| 1058 |
+
if not self._buffer:
|
| 1059 |
+
# Optimization: try to send now.
|
| 1060 |
+
try:
|
| 1061 |
+
n = self._sock.send(data)
|
| 1062 |
+
except (BlockingIOError, InterruptedError):
|
| 1063 |
+
pass
|
| 1064 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1065 |
+
raise
|
| 1066 |
+
except BaseException as exc:
|
| 1067 |
+
self._fatal_error(exc, 'Fatal write error on socket transport')
|
| 1068 |
+
return
|
| 1069 |
+
else:
|
| 1070 |
+
data = data[n:]
|
| 1071 |
+
if not data:
|
| 1072 |
+
return
|
| 1073 |
+
# Not all was written; register write handler.
|
| 1074 |
+
self._loop._add_writer(self._sock_fd, self._write_ready)
|
| 1075 |
+
|
| 1076 |
+
# Add it to the buffer.
|
| 1077 |
+
self._buffer.extend(data)
|
| 1078 |
+
self._maybe_pause_protocol()
|
| 1079 |
+
|
| 1080 |
+
def _write_ready(self):
|
| 1081 |
+
assert self._buffer, 'Data should not be empty'
|
| 1082 |
+
|
| 1083 |
+
if self._conn_lost:
|
| 1084 |
+
return
|
| 1085 |
+
try:
|
| 1086 |
+
n = self._sock.send(self._buffer)
|
| 1087 |
+
except (BlockingIOError, InterruptedError):
|
| 1088 |
+
pass
|
| 1089 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1090 |
+
raise
|
| 1091 |
+
except BaseException as exc:
|
| 1092 |
+
self._loop._remove_writer(self._sock_fd)
|
| 1093 |
+
self._buffer.clear()
|
| 1094 |
+
self._fatal_error(exc, 'Fatal write error on socket transport')
|
| 1095 |
+
if self._empty_waiter is not None:
|
| 1096 |
+
self._empty_waiter.set_exception(exc)
|
| 1097 |
+
else:
|
| 1098 |
+
if n:
|
| 1099 |
+
del self._buffer[:n]
|
| 1100 |
+
self._maybe_resume_protocol() # May append to buffer.
|
| 1101 |
+
if not self._buffer:
|
| 1102 |
+
self._loop._remove_writer(self._sock_fd)
|
| 1103 |
+
if self._empty_waiter is not None:
|
| 1104 |
+
self._empty_waiter.set_result(None)
|
| 1105 |
+
if self._closing:
|
| 1106 |
+
self._call_connection_lost(None)
|
| 1107 |
+
elif self._eof:
|
| 1108 |
+
self._sock.shutdown(socket.SHUT_WR)
|
| 1109 |
+
|
| 1110 |
+
def write_eof(self):
|
| 1111 |
+
if self._closing or self._eof:
|
| 1112 |
+
return
|
| 1113 |
+
self._eof = True
|
| 1114 |
+
if not self._buffer:
|
| 1115 |
+
self._sock.shutdown(socket.SHUT_WR)
|
| 1116 |
+
|
| 1117 |
+
def can_write_eof(self):
|
| 1118 |
+
return True
|
| 1119 |
+
|
| 1120 |
+
def _call_connection_lost(self, exc):
|
| 1121 |
+
super()._call_connection_lost(exc)
|
| 1122 |
+
if self._empty_waiter is not None:
|
| 1123 |
+
self._empty_waiter.set_exception(
|
| 1124 |
+
ConnectionError("Connection is closed by peer"))
|
| 1125 |
+
|
| 1126 |
+
def _make_empty_waiter(self):
|
| 1127 |
+
if self._empty_waiter is not None:
|
| 1128 |
+
raise RuntimeError("Empty waiter is already set")
|
| 1129 |
+
self._empty_waiter = self._loop.create_future()
|
| 1130 |
+
if not self._buffer:
|
| 1131 |
+
self._empty_waiter.set_result(None)
|
| 1132 |
+
return self._empty_waiter
|
| 1133 |
+
|
| 1134 |
+
def _reset_empty_waiter(self):
|
| 1135 |
+
self._empty_waiter = None
|
| 1136 |
+
|
| 1137 |
+
|
| 1138 |
+
class _SelectorDatagramTransport(_SelectorTransport):
|
| 1139 |
+
|
| 1140 |
+
_buffer_factory = collections.deque
|
| 1141 |
+
|
| 1142 |
+
def __init__(self, loop, sock, protocol, address=None,
|
| 1143 |
+
waiter=None, extra=None):
|
| 1144 |
+
super().__init__(loop, sock, protocol, extra)
|
| 1145 |
+
self._address = address
|
| 1146 |
+
self._buffer_size = 0
|
| 1147 |
+
self._loop.call_soon(self._protocol.connection_made, self)
|
| 1148 |
+
# only start reading when connection_made() has been called
|
| 1149 |
+
self._loop.call_soon(self._add_reader,
|
| 1150 |
+
self._sock_fd, self._read_ready)
|
| 1151 |
+
if waiter is not None:
|
| 1152 |
+
# only wake up the waiter when connection_made() has been called
|
| 1153 |
+
self._loop.call_soon(futures._set_result_unless_cancelled,
|
| 1154 |
+
waiter, None)
|
| 1155 |
+
|
| 1156 |
+
def get_write_buffer_size(self):
|
| 1157 |
+
return self._buffer_size
|
| 1158 |
+
|
| 1159 |
+
def _read_ready(self):
|
| 1160 |
+
if self._conn_lost:
|
| 1161 |
+
return
|
| 1162 |
+
try:
|
| 1163 |
+
data, addr = self._sock.recvfrom(self.max_size)
|
| 1164 |
+
except (BlockingIOError, InterruptedError):
|
| 1165 |
+
pass
|
| 1166 |
+
except OSError as exc:
|
| 1167 |
+
self._protocol.error_received(exc)
|
| 1168 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1169 |
+
raise
|
| 1170 |
+
except BaseException as exc:
|
| 1171 |
+
self._fatal_error(exc, 'Fatal read error on datagram transport')
|
| 1172 |
+
else:
|
| 1173 |
+
self._protocol.datagram_received(data, addr)
|
| 1174 |
+
|
| 1175 |
+
def sendto(self, data, addr=None):
|
| 1176 |
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
| 1177 |
+
raise TypeError(f'data argument must be a bytes-like object, '
|
| 1178 |
+
f'not {type(data).__name__!r}')
|
| 1179 |
+
if not data:
|
| 1180 |
+
return
|
| 1181 |
+
|
| 1182 |
+
if self._address:
|
| 1183 |
+
if addr not in (None, self._address):
|
| 1184 |
+
raise ValueError(
|
| 1185 |
+
f'Invalid address: must be None or {self._address}')
|
| 1186 |
+
addr = self._address
|
| 1187 |
+
|
| 1188 |
+
if self._conn_lost and self._address:
|
| 1189 |
+
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
|
| 1190 |
+
logger.warning('socket.send() raised exception.')
|
| 1191 |
+
self._conn_lost += 1
|
| 1192 |
+
return
|
| 1193 |
+
|
| 1194 |
+
if not self._buffer:
|
| 1195 |
+
# Attempt to send it right away first.
|
| 1196 |
+
try:
|
| 1197 |
+
if self._extra['peername']:
|
| 1198 |
+
self._sock.send(data)
|
| 1199 |
+
else:
|
| 1200 |
+
self._sock.sendto(data, addr)
|
| 1201 |
+
return
|
| 1202 |
+
except (BlockingIOError, InterruptedError):
|
| 1203 |
+
self._loop._add_writer(self._sock_fd, self._sendto_ready)
|
| 1204 |
+
except OSError as exc:
|
| 1205 |
+
self._protocol.error_received(exc)
|
| 1206 |
+
return
|
| 1207 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1208 |
+
raise
|
| 1209 |
+
except BaseException as exc:
|
| 1210 |
+
self._fatal_error(
|
| 1211 |
+
exc, 'Fatal write error on datagram transport')
|
| 1212 |
+
return
|
| 1213 |
+
|
| 1214 |
+
# Ensure that what we buffer is immutable.
|
| 1215 |
+
self._buffer.append((bytes(data), addr))
|
| 1216 |
+
self._buffer_size += len(data)
|
| 1217 |
+
self._maybe_pause_protocol()
|
| 1218 |
+
|
| 1219 |
+
def _sendto_ready(self):
|
| 1220 |
+
while self._buffer:
|
| 1221 |
+
data, addr = self._buffer.popleft()
|
| 1222 |
+
self._buffer_size -= len(data)
|
| 1223 |
+
try:
|
| 1224 |
+
if self._extra['peername']:
|
| 1225 |
+
self._sock.send(data)
|
| 1226 |
+
else:
|
| 1227 |
+
self._sock.sendto(data, addr)
|
| 1228 |
+
except (BlockingIOError, InterruptedError):
|
| 1229 |
+
self._buffer.appendleft((data, addr)) # Try again later.
|
| 1230 |
+
self._buffer_size += len(data)
|
| 1231 |
+
break
|
| 1232 |
+
except OSError as exc:
|
| 1233 |
+
self._protocol.error_received(exc)
|
| 1234 |
+
return
|
| 1235 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1236 |
+
raise
|
| 1237 |
+
except BaseException as exc:
|
| 1238 |
+
self._fatal_error(
|
| 1239 |
+
exc, 'Fatal write error on datagram transport')
|
| 1240 |
+
return
|
| 1241 |
+
|
| 1242 |
+
self._maybe_resume_protocol() # May append to buffer.
|
| 1243 |
+
if not self._buffer:
|
| 1244 |
+
self._loop._remove_writer(self._sock_fd)
|
| 1245 |
+
if self._closing:
|
| 1246 |
+
self._call_connection_lost(None)
|
micromamba_root/envs/pytorch_env/Lib/asyncio/sslproto.py
ADDED
|
@@ -0,0 +1,926 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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https://github.com/MagicStack/uvloop/tree/v0.16.0
|
| 2 |
+
# SPDX-License-Identifier: PSF-2.0 AND (MIT OR Apache-2.0)
|
| 3 |
+
# SPDX-FileCopyrightText: Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
|
| 4 |
+
|
| 5 |
+
import collections
|
| 6 |
+
import enum
|
| 7 |
+
import warnings
|
| 8 |
+
try:
|
| 9 |
+
import ssl
|
| 10 |
+
except ImportError: # pragma: no cover
|
| 11 |
+
ssl = None
|
| 12 |
+
|
| 13 |
+
from . import constants
|
| 14 |
+
from . import exceptions
|
| 15 |
+
from . import protocols
|
| 16 |
+
from . import transports
|
| 17 |
+
from .log import logger
|
| 18 |
+
|
| 19 |
+
if ssl is not None:
|
| 20 |
+
SSLAgainErrors = (ssl.SSLWantReadError, ssl.SSLSyscallError)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class SSLProtocolState(enum.Enum):
|
| 24 |
+
UNWRAPPED = "UNWRAPPED"
|
| 25 |
+
DO_HANDSHAKE = "DO_HANDSHAKE"
|
| 26 |
+
WRAPPED = "WRAPPED"
|
| 27 |
+
FLUSHING = "FLUSHING"
|
| 28 |
+
SHUTDOWN = "SHUTDOWN"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class AppProtocolState(enum.Enum):
|
| 32 |
+
# This tracks the state of app protocol (https://git.io/fj59P):
|
| 33 |
+
#
|
| 34 |
+
# INIT -cm-> CON_MADE [-dr*->] [-er-> EOF?] -cl-> CON_LOST
|
| 35 |
+
#
|
| 36 |
+
# * cm: connection_made()
|
| 37 |
+
# * dr: data_received()
|
| 38 |
+
# * er: eof_received()
|
| 39 |
+
# * cl: connection_lost()
|
| 40 |
+
|
| 41 |
+
STATE_INIT = "STATE_INIT"
|
| 42 |
+
STATE_CON_MADE = "STATE_CON_MADE"
|
| 43 |
+
STATE_EOF = "STATE_EOF"
|
| 44 |
+
STATE_CON_LOST = "STATE_CON_LOST"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _create_transport_context(server_side, server_hostname):
|
| 48 |
+
if server_side:
|
| 49 |
+
raise ValueError('Server side SSL needs a valid SSLContext')
|
| 50 |
+
|
| 51 |
+
# Client side may pass ssl=True to use a default
|
| 52 |
+
# context; in that case the sslcontext passed is None.
|
| 53 |
+
# The default is secure for client connections.
|
| 54 |
+
# Python 3.4+: use up-to-date strong settings.
|
| 55 |
+
sslcontext = ssl.create_default_context()
|
| 56 |
+
if not server_hostname:
|
| 57 |
+
sslcontext.check_hostname = False
|
| 58 |
+
return sslcontext
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def add_flowcontrol_defaults(high, low, kb):
|
| 62 |
+
if high is None:
|
| 63 |
+
if low is None:
|
| 64 |
+
hi = kb * 1024
|
| 65 |
+
else:
|
| 66 |
+
lo = low
|
| 67 |
+
hi = 4 * lo
|
| 68 |
+
else:
|
| 69 |
+
hi = high
|
| 70 |
+
if low is None:
|
| 71 |
+
lo = hi // 4
|
| 72 |
+
else:
|
| 73 |
+
lo = low
|
| 74 |
+
|
| 75 |
+
if not hi >= lo >= 0:
|
| 76 |
+
raise ValueError('high (%r) must be >= low (%r) must be >= 0' %
|
| 77 |
+
(hi, lo))
|
| 78 |
+
|
| 79 |
+
return hi, lo
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class _SSLProtocolTransport(transports._FlowControlMixin,
|
| 83 |
+
transports.Transport):
|
| 84 |
+
|
| 85 |
+
_start_tls_compatible = True
|
| 86 |
+
_sendfile_compatible = constants._SendfileMode.FALLBACK
|
| 87 |
+
|
| 88 |
+
def __init__(self, loop, ssl_protocol):
|
| 89 |
+
self._loop = loop
|
| 90 |
+
self._ssl_protocol = ssl_protocol
|
| 91 |
+
self._closed = False
|
| 92 |
+
|
| 93 |
+
def get_extra_info(self, name, default=None):
|
| 94 |
+
"""Get optional transport information."""
|
| 95 |
+
return self._ssl_protocol._get_extra_info(name, default)
|
| 96 |
+
|
| 97 |
+
def set_protocol(self, protocol):
|
| 98 |
+
self._ssl_protocol._set_app_protocol(protocol)
|
| 99 |
+
|
| 100 |
+
def get_protocol(self):
|
| 101 |
+
return self._ssl_protocol._app_protocol
|
| 102 |
+
|
| 103 |
+
def is_closing(self):
|
| 104 |
+
return self._closed
|
| 105 |
+
|
| 106 |
+
def close(self):
|
| 107 |
+
"""Close the transport.
|
| 108 |
+
|
| 109 |
+
Buffered data will be flushed asynchronously. No more data
|
| 110 |
+
will be received. After all buffered data is flushed, the
|
| 111 |
+
protocol's connection_lost() method will (eventually) called
|
| 112 |
+
with None as its argument.
|
| 113 |
+
"""
|
| 114 |
+
if not self._closed:
|
| 115 |
+
self._closed = True
|
| 116 |
+
self._ssl_protocol._start_shutdown()
|
| 117 |
+
else:
|
| 118 |
+
self._ssl_protocol = None
|
| 119 |
+
|
| 120 |
+
def __del__(self, _warnings=warnings):
|
| 121 |
+
if not self._closed:
|
| 122 |
+
self._closed = True
|
| 123 |
+
_warnings.warn(
|
| 124 |
+
"unclosed transport <asyncio._SSLProtocolTransport "
|
| 125 |
+
"object>", ResourceWarning)
|
| 126 |
+
|
| 127 |
+
def is_reading(self):
|
| 128 |
+
return not self._ssl_protocol._app_reading_paused
|
| 129 |
+
|
| 130 |
+
def pause_reading(self):
|
| 131 |
+
"""Pause the receiving end.
|
| 132 |
+
|
| 133 |
+
No data will be passed to the protocol's data_received()
|
| 134 |
+
method until resume_reading() is called.
|
| 135 |
+
"""
|
| 136 |
+
self._ssl_protocol._pause_reading()
|
| 137 |
+
|
| 138 |
+
def resume_reading(self):
|
| 139 |
+
"""Resume the receiving end.
|
| 140 |
+
|
| 141 |
+
Data received will once again be passed to the protocol's
|
| 142 |
+
data_received() method.
|
| 143 |
+
"""
|
| 144 |
+
self._ssl_protocol._resume_reading()
|
| 145 |
+
|
| 146 |
+
def set_write_buffer_limits(self, high=None, low=None):
|
| 147 |
+
"""Set the high- and low-water limits for write flow control.
|
| 148 |
+
|
| 149 |
+
These two values control when to call the protocol's
|
| 150 |
+
pause_writing() and resume_writing() methods. If specified,
|
| 151 |
+
the low-water limit must be less than or equal to the
|
| 152 |
+
high-water limit. Neither value can be negative.
|
| 153 |
+
|
| 154 |
+
The defaults are implementation-specific. If only the
|
| 155 |
+
high-water limit is given, the low-water limit defaults to an
|
| 156 |
+
implementation-specific value less than or equal to the
|
| 157 |
+
high-water limit. Setting high to zero forces low to zero as
|
| 158 |
+
well, and causes pause_writing() to be called whenever the
|
| 159 |
+
buffer becomes non-empty. Setting low to zero causes
|
| 160 |
+
resume_writing() to be called only once the buffer is empty.
|
| 161 |
+
Use of zero for either limit is generally sub-optimal as it
|
| 162 |
+
reduces opportunities for doing I/O and computation
|
| 163 |
+
concurrently.
|
| 164 |
+
"""
|
| 165 |
+
self._ssl_protocol._set_write_buffer_limits(high, low)
|
| 166 |
+
self._ssl_protocol._control_app_writing()
|
| 167 |
+
|
| 168 |
+
def get_write_buffer_limits(self):
|
| 169 |
+
return (self._ssl_protocol._outgoing_low_water,
|
| 170 |
+
self._ssl_protocol._outgoing_high_water)
|
| 171 |
+
|
| 172 |
+
def get_write_buffer_size(self):
|
| 173 |
+
"""Return the current size of the write buffers."""
|
| 174 |
+
return self._ssl_protocol._get_write_buffer_size()
|
| 175 |
+
|
| 176 |
+
def set_read_buffer_limits(self, high=None, low=None):
|
| 177 |
+
"""Set the high- and low-water limits for read flow control.
|
| 178 |
+
|
| 179 |
+
These two values control when to call the upstream transport's
|
| 180 |
+
pause_reading() and resume_reading() methods. If specified,
|
| 181 |
+
the low-water limit must be less than or equal to the
|
| 182 |
+
high-water limit. Neither value can be negative.
|
| 183 |
+
|
| 184 |
+
The defaults are implementation-specific. If only the
|
| 185 |
+
high-water limit is given, the low-water limit defaults to an
|
| 186 |
+
implementation-specific value less than or equal to the
|
| 187 |
+
high-water limit. Setting high to zero forces low to zero as
|
| 188 |
+
well, and causes pause_reading() to be called whenever the
|
| 189 |
+
buffer becomes non-empty. Setting low to zero causes
|
| 190 |
+
resume_reading() to be called only once the buffer is empty.
|
| 191 |
+
Use of zero for either limit is generally sub-optimal as it
|
| 192 |
+
reduces opportunities for doing I/O and computation
|
| 193 |
+
concurrently.
|
| 194 |
+
"""
|
| 195 |
+
self._ssl_protocol._set_read_buffer_limits(high, low)
|
| 196 |
+
self._ssl_protocol._control_ssl_reading()
|
| 197 |
+
|
| 198 |
+
def get_read_buffer_limits(self):
|
| 199 |
+
return (self._ssl_protocol._incoming_low_water,
|
| 200 |
+
self._ssl_protocol._incoming_high_water)
|
| 201 |
+
|
| 202 |
+
def get_read_buffer_size(self):
|
| 203 |
+
"""Return the current size of the read buffer."""
|
| 204 |
+
return self._ssl_protocol._get_read_buffer_size()
|
| 205 |
+
|
| 206 |
+
@property
|
| 207 |
+
def _protocol_paused(self):
|
| 208 |
+
# Required for sendfile fallback pause_writing/resume_writing logic
|
| 209 |
+
return self._ssl_protocol._app_writing_paused
|
| 210 |
+
|
| 211 |
+
def write(self, data):
|
| 212 |
+
"""Write some data bytes to the transport.
|
| 213 |
+
|
| 214 |
+
This does not block; it buffers the data and arranges for it
|
| 215 |
+
to be sent out asynchronously.
|
| 216 |
+
"""
|
| 217 |
+
if not isinstance(data, (bytes, bytearray, memoryview)):
|
| 218 |
+
raise TypeError(f"data: expecting a bytes-like instance, "
|
| 219 |
+
f"got {type(data).__name__}")
|
| 220 |
+
if not data:
|
| 221 |
+
return
|
| 222 |
+
self._ssl_protocol._write_appdata((data,))
|
| 223 |
+
|
| 224 |
+
def writelines(self, list_of_data):
|
| 225 |
+
"""Write a list (or any iterable) of data bytes to the transport.
|
| 226 |
+
|
| 227 |
+
The default implementation concatenates the arguments and
|
| 228 |
+
calls write() on the result.
|
| 229 |
+
"""
|
| 230 |
+
self._ssl_protocol._write_appdata(list_of_data)
|
| 231 |
+
|
| 232 |
+
def write_eof(self):
|
| 233 |
+
"""Close the write end after flushing buffered data.
|
| 234 |
+
|
| 235 |
+
This raises :exc:`NotImplementedError` right now.
|
| 236 |
+
"""
|
| 237 |
+
raise NotImplementedError
|
| 238 |
+
|
| 239 |
+
def can_write_eof(self):
|
| 240 |
+
"""Return True if this transport supports write_eof(), False if not."""
|
| 241 |
+
return False
|
| 242 |
+
|
| 243 |
+
def abort(self):
|
| 244 |
+
"""Close the transport immediately.
|
| 245 |
+
|
| 246 |
+
Buffered data will be lost. No more data will be received.
|
| 247 |
+
The protocol's connection_lost() method will (eventually) be
|
| 248 |
+
called with None as its argument.
|
| 249 |
+
"""
|
| 250 |
+
self._force_close(None)
|
| 251 |
+
|
| 252 |
+
def _force_close(self, exc):
|
| 253 |
+
self._closed = True
|
| 254 |
+
if self._ssl_protocol is not None:
|
| 255 |
+
self._ssl_protocol._abort(exc)
|
| 256 |
+
|
| 257 |
+
def _test__append_write_backlog(self, data):
|
| 258 |
+
# for test only
|
| 259 |
+
self._ssl_protocol._write_backlog.append(data)
|
| 260 |
+
self._ssl_protocol._write_buffer_size += len(data)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
class SSLProtocol(protocols.BufferedProtocol):
|
| 264 |
+
max_size = 256 * 1024 # Buffer size passed to read()
|
| 265 |
+
|
| 266 |
+
_handshake_start_time = None
|
| 267 |
+
_handshake_timeout_handle = None
|
| 268 |
+
_shutdown_timeout_handle = None
|
| 269 |
+
|
| 270 |
+
def __init__(self, loop, app_protocol, sslcontext, waiter,
|
| 271 |
+
server_side=False, server_hostname=None,
|
| 272 |
+
call_connection_made=True,
|
| 273 |
+
ssl_handshake_timeout=None,
|
| 274 |
+
ssl_shutdown_timeout=None):
|
| 275 |
+
if ssl is None:
|
| 276 |
+
raise RuntimeError("stdlib ssl module not available")
|
| 277 |
+
|
| 278 |
+
self._ssl_buffer = bytearray(self.max_size)
|
| 279 |
+
self._ssl_buffer_view = memoryview(self._ssl_buffer)
|
| 280 |
+
|
| 281 |
+
if ssl_handshake_timeout is None:
|
| 282 |
+
ssl_handshake_timeout = constants.SSL_HANDSHAKE_TIMEOUT
|
| 283 |
+
elif ssl_handshake_timeout <= 0:
|
| 284 |
+
raise ValueError(
|
| 285 |
+
f"ssl_handshake_timeout should be a positive number, "
|
| 286 |
+
f"got {ssl_handshake_timeout}")
|
| 287 |
+
if ssl_shutdown_timeout is None:
|
| 288 |
+
ssl_shutdown_timeout = constants.SSL_SHUTDOWN_TIMEOUT
|
| 289 |
+
elif ssl_shutdown_timeout <= 0:
|
| 290 |
+
raise ValueError(
|
| 291 |
+
f"ssl_shutdown_timeout should be a positive number, "
|
| 292 |
+
f"got {ssl_shutdown_timeout}")
|
| 293 |
+
|
| 294 |
+
if not sslcontext:
|
| 295 |
+
sslcontext = _create_transport_context(
|
| 296 |
+
server_side, server_hostname)
|
| 297 |
+
|
| 298 |
+
self._server_side = server_side
|
| 299 |
+
if server_hostname and not server_side:
|
| 300 |
+
self._server_hostname = server_hostname
|
| 301 |
+
else:
|
| 302 |
+
self._server_hostname = None
|
| 303 |
+
self._sslcontext = sslcontext
|
| 304 |
+
# SSL-specific extra info. More info are set when the handshake
|
| 305 |
+
# completes.
|
| 306 |
+
self._extra = dict(sslcontext=sslcontext)
|
| 307 |
+
|
| 308 |
+
# App data write buffering
|
| 309 |
+
self._write_backlog = collections.deque()
|
| 310 |
+
self._write_buffer_size = 0
|
| 311 |
+
|
| 312 |
+
self._waiter = waiter
|
| 313 |
+
self._loop = loop
|
| 314 |
+
self._set_app_protocol(app_protocol)
|
| 315 |
+
self._app_transport = None
|
| 316 |
+
self._app_transport_created = False
|
| 317 |
+
# transport, ex: SelectorSocketTransport
|
| 318 |
+
self._transport = None
|
| 319 |
+
self._ssl_handshake_timeout = ssl_handshake_timeout
|
| 320 |
+
self._ssl_shutdown_timeout = ssl_shutdown_timeout
|
| 321 |
+
# SSL and state machine
|
| 322 |
+
self._incoming = ssl.MemoryBIO()
|
| 323 |
+
self._outgoing = ssl.MemoryBIO()
|
| 324 |
+
self._state = SSLProtocolState.UNWRAPPED
|
| 325 |
+
self._conn_lost = 0 # Set when connection_lost called
|
| 326 |
+
if call_connection_made:
|
| 327 |
+
self._app_state = AppProtocolState.STATE_INIT
|
| 328 |
+
else:
|
| 329 |
+
self._app_state = AppProtocolState.STATE_CON_MADE
|
| 330 |
+
self._sslobj = self._sslcontext.wrap_bio(
|
| 331 |
+
self._incoming, self._outgoing,
|
| 332 |
+
server_side=self._server_side,
|
| 333 |
+
server_hostname=self._server_hostname)
|
| 334 |
+
|
| 335 |
+
# Flow Control
|
| 336 |
+
|
| 337 |
+
self._ssl_writing_paused = False
|
| 338 |
+
|
| 339 |
+
self._app_reading_paused = False
|
| 340 |
+
|
| 341 |
+
self._ssl_reading_paused = False
|
| 342 |
+
self._incoming_high_water = 0
|
| 343 |
+
self._incoming_low_water = 0
|
| 344 |
+
self._set_read_buffer_limits()
|
| 345 |
+
self._eof_received = False
|
| 346 |
+
|
| 347 |
+
self._app_writing_paused = False
|
| 348 |
+
self._outgoing_high_water = 0
|
| 349 |
+
self._outgoing_low_water = 0
|
| 350 |
+
self._set_write_buffer_limits()
|
| 351 |
+
self._get_app_transport()
|
| 352 |
+
|
| 353 |
+
def _set_app_protocol(self, app_protocol):
|
| 354 |
+
self._app_protocol = app_protocol
|
| 355 |
+
# Make fast hasattr check first
|
| 356 |
+
if (hasattr(app_protocol, 'get_buffer') and
|
| 357 |
+
isinstance(app_protocol, protocols.BufferedProtocol)):
|
| 358 |
+
self._app_protocol_get_buffer = app_protocol.get_buffer
|
| 359 |
+
self._app_protocol_buffer_updated = app_protocol.buffer_updated
|
| 360 |
+
self._app_protocol_is_buffer = True
|
| 361 |
+
else:
|
| 362 |
+
self._app_protocol_is_buffer = False
|
| 363 |
+
|
| 364 |
+
def _wakeup_waiter(self, exc=None):
|
| 365 |
+
if self._waiter is None:
|
| 366 |
+
return
|
| 367 |
+
if not self._waiter.cancelled():
|
| 368 |
+
if exc is not None:
|
| 369 |
+
self._waiter.set_exception(exc)
|
| 370 |
+
else:
|
| 371 |
+
self._waiter.set_result(None)
|
| 372 |
+
self._waiter = None
|
| 373 |
+
|
| 374 |
+
def _get_app_transport(self):
|
| 375 |
+
if self._app_transport is None:
|
| 376 |
+
if self._app_transport_created:
|
| 377 |
+
raise RuntimeError('Creating _SSLProtocolTransport twice')
|
| 378 |
+
self._app_transport = _SSLProtocolTransport(self._loop, self)
|
| 379 |
+
self._app_transport_created = True
|
| 380 |
+
return self._app_transport
|
| 381 |
+
|
| 382 |
+
def connection_made(self, transport):
|
| 383 |
+
"""Called when the low-level connection is made.
|
| 384 |
+
|
| 385 |
+
Start the SSL handshake.
|
| 386 |
+
"""
|
| 387 |
+
self._transport = transport
|
| 388 |
+
self._start_handshake()
|
| 389 |
+
|
| 390 |
+
def connection_lost(self, exc):
|
| 391 |
+
"""Called when the low-level connection is lost or closed.
|
| 392 |
+
|
| 393 |
+
The argument is an exception object or None (the latter
|
| 394 |
+
meaning a regular EOF is received or the connection was
|
| 395 |
+
aborted or closed).
|
| 396 |
+
"""
|
| 397 |
+
self._write_backlog.clear()
|
| 398 |
+
self._outgoing.read()
|
| 399 |
+
self._conn_lost += 1
|
| 400 |
+
|
| 401 |
+
# Just mark the app transport as closed so that its __dealloc__
|
| 402 |
+
# doesn't complain.
|
| 403 |
+
if self._app_transport is not None:
|
| 404 |
+
self._app_transport._closed = True
|
| 405 |
+
|
| 406 |
+
if self._state != SSLProtocolState.DO_HANDSHAKE:
|
| 407 |
+
if (
|
| 408 |
+
self._app_state == AppProtocolState.STATE_CON_MADE or
|
| 409 |
+
self._app_state == AppProtocolState.STATE_EOF
|
| 410 |
+
):
|
| 411 |
+
self._app_state = AppProtocolState.STATE_CON_LOST
|
| 412 |
+
self._loop.call_soon(self._app_protocol.connection_lost, exc)
|
| 413 |
+
self._set_state(SSLProtocolState.UNWRAPPED)
|
| 414 |
+
self._transport = None
|
| 415 |
+
self._app_transport = None
|
| 416 |
+
self._app_protocol = None
|
| 417 |
+
self._wakeup_waiter(exc)
|
| 418 |
+
|
| 419 |
+
if self._shutdown_timeout_handle:
|
| 420 |
+
self._shutdown_timeout_handle.cancel()
|
| 421 |
+
self._shutdown_timeout_handle = None
|
| 422 |
+
if self._handshake_timeout_handle:
|
| 423 |
+
self._handshake_timeout_handle.cancel()
|
| 424 |
+
self._handshake_timeout_handle = None
|
| 425 |
+
|
| 426 |
+
def get_buffer(self, n):
|
| 427 |
+
want = n
|
| 428 |
+
if want <= 0 or want > self.max_size:
|
| 429 |
+
want = self.max_size
|
| 430 |
+
if len(self._ssl_buffer) < want:
|
| 431 |
+
self._ssl_buffer = bytearray(want)
|
| 432 |
+
self._ssl_buffer_view = memoryview(self._ssl_buffer)
|
| 433 |
+
return self._ssl_buffer_view
|
| 434 |
+
|
| 435 |
+
def buffer_updated(self, nbytes):
|
| 436 |
+
self._incoming.write(self._ssl_buffer_view[:nbytes])
|
| 437 |
+
|
| 438 |
+
if self._state == SSLProtocolState.DO_HANDSHAKE:
|
| 439 |
+
self._do_handshake()
|
| 440 |
+
|
| 441 |
+
elif self._state == SSLProtocolState.WRAPPED:
|
| 442 |
+
self._do_read()
|
| 443 |
+
|
| 444 |
+
elif self._state == SSLProtocolState.FLUSHING:
|
| 445 |
+
self._do_flush()
|
| 446 |
+
|
| 447 |
+
elif self._state == SSLProtocolState.SHUTDOWN:
|
| 448 |
+
self._do_shutdown()
|
| 449 |
+
|
| 450 |
+
def eof_received(self):
|
| 451 |
+
"""Called when the other end of the low-level stream
|
| 452 |
+
is half-closed.
|
| 453 |
+
|
| 454 |
+
If this returns a false value (including None), the transport
|
| 455 |
+
will close itself. If it returns a true value, closing the
|
| 456 |
+
transport is up to the protocol.
|
| 457 |
+
"""
|
| 458 |
+
self._eof_received = True
|
| 459 |
+
try:
|
| 460 |
+
if self._loop.get_debug():
|
| 461 |
+
logger.debug("%r received EOF", self)
|
| 462 |
+
|
| 463 |
+
if self._state == SSLProtocolState.DO_HANDSHAKE:
|
| 464 |
+
self._on_handshake_complete(ConnectionResetError)
|
| 465 |
+
|
| 466 |
+
elif self._state == SSLProtocolState.WRAPPED:
|
| 467 |
+
self._set_state(SSLProtocolState.FLUSHING)
|
| 468 |
+
if self._app_reading_paused:
|
| 469 |
+
return True
|
| 470 |
+
else:
|
| 471 |
+
self._do_flush()
|
| 472 |
+
|
| 473 |
+
elif self._state == SSLProtocolState.FLUSHING:
|
| 474 |
+
self._do_write()
|
| 475 |
+
self._set_state(SSLProtocolState.SHUTDOWN)
|
| 476 |
+
self._do_shutdown()
|
| 477 |
+
|
| 478 |
+
elif self._state == SSLProtocolState.SHUTDOWN:
|
| 479 |
+
self._do_shutdown()
|
| 480 |
+
|
| 481 |
+
except Exception:
|
| 482 |
+
self._transport.close()
|
| 483 |
+
raise
|
| 484 |
+
|
| 485 |
+
def _get_extra_info(self, name, default=None):
|
| 486 |
+
if name in self._extra:
|
| 487 |
+
return self._extra[name]
|
| 488 |
+
elif self._transport is not None:
|
| 489 |
+
return self._transport.get_extra_info(name, default)
|
| 490 |
+
else:
|
| 491 |
+
return default
|
| 492 |
+
|
| 493 |
+
def _set_state(self, new_state):
|
| 494 |
+
allowed = False
|
| 495 |
+
|
| 496 |
+
if new_state == SSLProtocolState.UNWRAPPED:
|
| 497 |
+
allowed = True
|
| 498 |
+
|
| 499 |
+
elif (
|
| 500 |
+
self._state == SSLProtocolState.UNWRAPPED and
|
| 501 |
+
new_state == SSLProtocolState.DO_HANDSHAKE
|
| 502 |
+
):
|
| 503 |
+
allowed = True
|
| 504 |
+
|
| 505 |
+
elif (
|
| 506 |
+
self._state == SSLProtocolState.DO_HANDSHAKE and
|
| 507 |
+
new_state == SSLProtocolState.WRAPPED
|
| 508 |
+
):
|
| 509 |
+
allowed = True
|
| 510 |
+
|
| 511 |
+
elif (
|
| 512 |
+
self._state == SSLProtocolState.WRAPPED and
|
| 513 |
+
new_state == SSLProtocolState.FLUSHING
|
| 514 |
+
):
|
| 515 |
+
allowed = True
|
| 516 |
+
|
| 517 |
+
elif (
|
| 518 |
+
self._state == SSLProtocolState.FLUSHING and
|
| 519 |
+
new_state == SSLProtocolState.SHUTDOWN
|
| 520 |
+
):
|
| 521 |
+
allowed = True
|
| 522 |
+
|
| 523 |
+
if allowed:
|
| 524 |
+
self._state = new_state
|
| 525 |
+
|
| 526 |
+
else:
|
| 527 |
+
raise RuntimeError(
|
| 528 |
+
'cannot switch state from {} to {}'.format(
|
| 529 |
+
self._state, new_state))
|
| 530 |
+
|
| 531 |
+
# Handshake flow
|
| 532 |
+
|
| 533 |
+
def _start_handshake(self):
|
| 534 |
+
if self._loop.get_debug():
|
| 535 |
+
logger.debug("%r starts SSL handshake", self)
|
| 536 |
+
self._handshake_start_time = self._loop.time()
|
| 537 |
+
else:
|
| 538 |
+
self._handshake_start_time = None
|
| 539 |
+
|
| 540 |
+
self._set_state(SSLProtocolState.DO_HANDSHAKE)
|
| 541 |
+
|
| 542 |
+
# start handshake timeout count down
|
| 543 |
+
self._handshake_timeout_handle = \
|
| 544 |
+
self._loop.call_later(self._ssl_handshake_timeout,
|
| 545 |
+
lambda: self._check_handshake_timeout())
|
| 546 |
+
|
| 547 |
+
self._do_handshake()
|
| 548 |
+
|
| 549 |
+
def _check_handshake_timeout(self):
|
| 550 |
+
if self._state == SSLProtocolState.DO_HANDSHAKE:
|
| 551 |
+
msg = (
|
| 552 |
+
f"SSL handshake is taking longer than "
|
| 553 |
+
f"{self._ssl_handshake_timeout} seconds: "
|
| 554 |
+
f"aborting the connection"
|
| 555 |
+
)
|
| 556 |
+
self._fatal_error(ConnectionAbortedError(msg))
|
| 557 |
+
|
| 558 |
+
def _do_handshake(self):
|
| 559 |
+
try:
|
| 560 |
+
self._sslobj.do_handshake()
|
| 561 |
+
except SSLAgainErrors:
|
| 562 |
+
self._process_outgoing()
|
| 563 |
+
except ssl.SSLError as exc:
|
| 564 |
+
self._on_handshake_complete(exc)
|
| 565 |
+
else:
|
| 566 |
+
self._on_handshake_complete(None)
|
| 567 |
+
|
| 568 |
+
def _on_handshake_complete(self, handshake_exc):
|
| 569 |
+
if self._handshake_timeout_handle is not None:
|
| 570 |
+
self._handshake_timeout_handle.cancel()
|
| 571 |
+
self._handshake_timeout_handle = None
|
| 572 |
+
|
| 573 |
+
sslobj = self._sslobj
|
| 574 |
+
try:
|
| 575 |
+
if handshake_exc is None:
|
| 576 |
+
self._set_state(SSLProtocolState.WRAPPED)
|
| 577 |
+
else:
|
| 578 |
+
raise handshake_exc
|
| 579 |
+
|
| 580 |
+
peercert = sslobj.getpeercert()
|
| 581 |
+
except Exception as exc:
|
| 582 |
+
handshake_exc = None
|
| 583 |
+
self._set_state(SSLProtocolState.UNWRAPPED)
|
| 584 |
+
if isinstance(exc, ssl.CertificateError):
|
| 585 |
+
msg = 'SSL handshake failed on verifying the certificate'
|
| 586 |
+
else:
|
| 587 |
+
msg = 'SSL handshake failed'
|
| 588 |
+
self._fatal_error(exc, msg)
|
| 589 |
+
self._wakeup_waiter(exc)
|
| 590 |
+
return
|
| 591 |
+
|
| 592 |
+
if self._loop.get_debug():
|
| 593 |
+
dt = self._loop.time() - self._handshake_start_time
|
| 594 |
+
logger.debug("%r: SSL handshake took %.1f ms", self, dt * 1e3)
|
| 595 |
+
|
| 596 |
+
# Add extra info that becomes available after handshake.
|
| 597 |
+
self._extra.update(peercert=peercert,
|
| 598 |
+
cipher=sslobj.cipher(),
|
| 599 |
+
compression=sslobj.compression(),
|
| 600 |
+
ssl_object=sslobj)
|
| 601 |
+
if self._app_state == AppProtocolState.STATE_INIT:
|
| 602 |
+
self._app_state = AppProtocolState.STATE_CON_MADE
|
| 603 |
+
self._app_protocol.connection_made(self._get_app_transport())
|
| 604 |
+
self._wakeup_waiter()
|
| 605 |
+
self._do_read()
|
| 606 |
+
|
| 607 |
+
# Shutdown flow
|
| 608 |
+
|
| 609 |
+
def _start_shutdown(self):
|
| 610 |
+
if (
|
| 611 |
+
self._state in (
|
| 612 |
+
SSLProtocolState.FLUSHING,
|
| 613 |
+
SSLProtocolState.SHUTDOWN,
|
| 614 |
+
SSLProtocolState.UNWRAPPED
|
| 615 |
+
)
|
| 616 |
+
):
|
| 617 |
+
return
|
| 618 |
+
if self._app_transport is not None:
|
| 619 |
+
self._app_transport._closed = True
|
| 620 |
+
if self._state == SSLProtocolState.DO_HANDSHAKE:
|
| 621 |
+
self._abort(None)
|
| 622 |
+
else:
|
| 623 |
+
self._set_state(SSLProtocolState.FLUSHING)
|
| 624 |
+
self._shutdown_timeout_handle = self._loop.call_later(
|
| 625 |
+
self._ssl_shutdown_timeout,
|
| 626 |
+
lambda: self._check_shutdown_timeout()
|
| 627 |
+
)
|
| 628 |
+
self._do_flush()
|
| 629 |
+
|
| 630 |
+
def _check_shutdown_timeout(self):
|
| 631 |
+
if (
|
| 632 |
+
self._state in (
|
| 633 |
+
SSLProtocolState.FLUSHING,
|
| 634 |
+
SSLProtocolState.SHUTDOWN
|
| 635 |
+
)
|
| 636 |
+
):
|
| 637 |
+
self._transport._force_close(
|
| 638 |
+
exceptions.TimeoutError('SSL shutdown timed out'))
|
| 639 |
+
|
| 640 |
+
def _do_flush(self):
|
| 641 |
+
self._do_read()
|
| 642 |
+
self._set_state(SSLProtocolState.SHUTDOWN)
|
| 643 |
+
self._do_shutdown()
|
| 644 |
+
|
| 645 |
+
def _do_shutdown(self):
|
| 646 |
+
try:
|
| 647 |
+
if not self._eof_received:
|
| 648 |
+
self._sslobj.unwrap()
|
| 649 |
+
except SSLAgainErrors:
|
| 650 |
+
self._process_outgoing()
|
| 651 |
+
except ssl.SSLError as exc:
|
| 652 |
+
self._on_shutdown_complete(exc)
|
| 653 |
+
else:
|
| 654 |
+
self._process_outgoing()
|
| 655 |
+
self._call_eof_received()
|
| 656 |
+
self._on_shutdown_complete(None)
|
| 657 |
+
|
| 658 |
+
def _on_shutdown_complete(self, shutdown_exc):
|
| 659 |
+
if self._shutdown_timeout_handle is not None:
|
| 660 |
+
self._shutdown_timeout_handle.cancel()
|
| 661 |
+
self._shutdown_timeout_handle = None
|
| 662 |
+
|
| 663 |
+
if shutdown_exc:
|
| 664 |
+
self._fatal_error(shutdown_exc)
|
| 665 |
+
else:
|
| 666 |
+
self._loop.call_soon(self._transport.close)
|
| 667 |
+
|
| 668 |
+
def _abort(self, exc):
|
| 669 |
+
self._set_state(SSLProtocolState.UNWRAPPED)
|
| 670 |
+
if self._transport is not None:
|
| 671 |
+
self._transport._force_close(exc)
|
| 672 |
+
|
| 673 |
+
# Outgoing flow
|
| 674 |
+
|
| 675 |
+
def _write_appdata(self, list_of_data):
|
| 676 |
+
if (
|
| 677 |
+
self._state in (
|
| 678 |
+
SSLProtocolState.FLUSHING,
|
| 679 |
+
SSLProtocolState.SHUTDOWN,
|
| 680 |
+
SSLProtocolState.UNWRAPPED
|
| 681 |
+
)
|
| 682 |
+
):
|
| 683 |
+
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
|
| 684 |
+
logger.warning('SSL connection is closed')
|
| 685 |
+
self._conn_lost += 1
|
| 686 |
+
return
|
| 687 |
+
|
| 688 |
+
for data in list_of_data:
|
| 689 |
+
self._write_backlog.append(data)
|
| 690 |
+
self._write_buffer_size += len(data)
|
| 691 |
+
|
| 692 |
+
try:
|
| 693 |
+
if self._state == SSLProtocolState.WRAPPED:
|
| 694 |
+
self._do_write()
|
| 695 |
+
|
| 696 |
+
except Exception as ex:
|
| 697 |
+
self._fatal_error(ex, 'Fatal error on SSL protocol')
|
| 698 |
+
|
| 699 |
+
def _do_write(self):
|
| 700 |
+
try:
|
| 701 |
+
while self._write_backlog:
|
| 702 |
+
data = self._write_backlog[0]
|
| 703 |
+
count = self._sslobj.write(data)
|
| 704 |
+
data_len = len(data)
|
| 705 |
+
if count < data_len:
|
| 706 |
+
self._write_backlog[0] = data[count:]
|
| 707 |
+
self._write_buffer_size -= count
|
| 708 |
+
else:
|
| 709 |
+
del self._write_backlog[0]
|
| 710 |
+
self._write_buffer_size -= data_len
|
| 711 |
+
except SSLAgainErrors:
|
| 712 |
+
pass
|
| 713 |
+
self._process_outgoing()
|
| 714 |
+
|
| 715 |
+
def _process_outgoing(self):
|
| 716 |
+
if not self._ssl_writing_paused:
|
| 717 |
+
data = self._outgoing.read()
|
| 718 |
+
if len(data):
|
| 719 |
+
self._transport.write(data)
|
| 720 |
+
self._control_app_writing()
|
| 721 |
+
|
| 722 |
+
# Incoming flow
|
| 723 |
+
|
| 724 |
+
def _do_read(self):
|
| 725 |
+
if (
|
| 726 |
+
self._state not in (
|
| 727 |
+
SSLProtocolState.WRAPPED,
|
| 728 |
+
SSLProtocolState.FLUSHING,
|
| 729 |
+
)
|
| 730 |
+
):
|
| 731 |
+
return
|
| 732 |
+
try:
|
| 733 |
+
if not self._app_reading_paused:
|
| 734 |
+
if self._app_protocol_is_buffer:
|
| 735 |
+
self._do_read__buffered()
|
| 736 |
+
else:
|
| 737 |
+
self._do_read__copied()
|
| 738 |
+
if self._write_backlog:
|
| 739 |
+
self._do_write()
|
| 740 |
+
else:
|
| 741 |
+
self._process_outgoing()
|
| 742 |
+
self._control_ssl_reading()
|
| 743 |
+
except Exception as ex:
|
| 744 |
+
self._fatal_error(ex, 'Fatal error on SSL protocol')
|
| 745 |
+
|
| 746 |
+
def _do_read__buffered(self):
|
| 747 |
+
offset = 0
|
| 748 |
+
count = 1
|
| 749 |
+
|
| 750 |
+
buf = self._app_protocol_get_buffer(self._get_read_buffer_size())
|
| 751 |
+
wants = len(buf)
|
| 752 |
+
|
| 753 |
+
try:
|
| 754 |
+
count = self._sslobj.read(wants, buf)
|
| 755 |
+
|
| 756 |
+
if count > 0:
|
| 757 |
+
offset = count
|
| 758 |
+
while offset < wants:
|
| 759 |
+
count = self._sslobj.read(wants - offset, buf[offset:])
|
| 760 |
+
if count > 0:
|
| 761 |
+
offset += count
|
| 762 |
+
else:
|
| 763 |
+
break
|
| 764 |
+
else:
|
| 765 |
+
self._loop.call_soon(lambda: self._do_read())
|
| 766 |
+
except SSLAgainErrors:
|
| 767 |
+
pass
|
| 768 |
+
if offset > 0:
|
| 769 |
+
self._app_protocol_buffer_updated(offset)
|
| 770 |
+
if not count:
|
| 771 |
+
# close_notify
|
| 772 |
+
self._call_eof_received()
|
| 773 |
+
self._start_shutdown()
|
| 774 |
+
|
| 775 |
+
def _do_read__copied(self):
|
| 776 |
+
chunk = b'1'
|
| 777 |
+
zero = True
|
| 778 |
+
one = False
|
| 779 |
+
|
| 780 |
+
try:
|
| 781 |
+
while True:
|
| 782 |
+
chunk = self._sslobj.read(self.max_size)
|
| 783 |
+
if not chunk:
|
| 784 |
+
break
|
| 785 |
+
if zero:
|
| 786 |
+
zero = False
|
| 787 |
+
one = True
|
| 788 |
+
first = chunk
|
| 789 |
+
elif one:
|
| 790 |
+
one = False
|
| 791 |
+
data = [first, chunk]
|
| 792 |
+
else:
|
| 793 |
+
data.append(chunk)
|
| 794 |
+
except SSLAgainErrors:
|
| 795 |
+
pass
|
| 796 |
+
if one:
|
| 797 |
+
self._app_protocol.data_received(first)
|
| 798 |
+
elif not zero:
|
| 799 |
+
self._app_protocol.data_received(b''.join(data))
|
| 800 |
+
if not chunk:
|
| 801 |
+
# close_notify
|
| 802 |
+
self._call_eof_received()
|
| 803 |
+
self._start_shutdown()
|
| 804 |
+
|
| 805 |
+
def _call_eof_received(self):
|
| 806 |
+
try:
|
| 807 |
+
if self._app_state == AppProtocolState.STATE_CON_MADE:
|
| 808 |
+
self._app_state = AppProtocolState.STATE_EOF
|
| 809 |
+
keep_open = self._app_protocol.eof_received()
|
| 810 |
+
if keep_open:
|
| 811 |
+
logger.warning('returning true from eof_received() '
|
| 812 |
+
'has no effect when using ssl')
|
| 813 |
+
except (KeyboardInterrupt, SystemExit):
|
| 814 |
+
raise
|
| 815 |
+
except BaseException as ex:
|
| 816 |
+
self._fatal_error(ex, 'Error calling eof_received()')
|
| 817 |
+
|
| 818 |
+
# Flow control for writes from APP socket
|
| 819 |
+
|
| 820 |
+
def _control_app_writing(self):
|
| 821 |
+
size = self._get_write_buffer_size()
|
| 822 |
+
if size >= self._outgoing_high_water and not self._app_writing_paused:
|
| 823 |
+
self._app_writing_paused = True
|
| 824 |
+
try:
|
| 825 |
+
self._app_protocol.pause_writing()
|
| 826 |
+
except (KeyboardInterrupt, SystemExit):
|
| 827 |
+
raise
|
| 828 |
+
except BaseException as exc:
|
| 829 |
+
self._loop.call_exception_handler({
|
| 830 |
+
'message': 'protocol.pause_writing() failed',
|
| 831 |
+
'exception': exc,
|
| 832 |
+
'transport': self._app_transport,
|
| 833 |
+
'protocol': self,
|
| 834 |
+
})
|
| 835 |
+
elif size <= self._outgoing_low_water and self._app_writing_paused:
|
| 836 |
+
self._app_writing_paused = False
|
| 837 |
+
try:
|
| 838 |
+
self._app_protocol.resume_writing()
|
| 839 |
+
except (KeyboardInterrupt, SystemExit):
|
| 840 |
+
raise
|
| 841 |
+
except BaseException as exc:
|
| 842 |
+
self._loop.call_exception_handler({
|
| 843 |
+
'message': 'protocol.resume_writing() failed',
|
| 844 |
+
'exception': exc,
|
| 845 |
+
'transport': self._app_transport,
|
| 846 |
+
'protocol': self,
|
| 847 |
+
})
|
| 848 |
+
|
| 849 |
+
def _get_write_buffer_size(self):
|
| 850 |
+
return self._outgoing.pending + self._write_buffer_size
|
| 851 |
+
|
| 852 |
+
def _set_write_buffer_limits(self, high=None, low=None):
|
| 853 |
+
high, low = add_flowcontrol_defaults(
|
| 854 |
+
high, low, constants.FLOW_CONTROL_HIGH_WATER_SSL_WRITE)
|
| 855 |
+
self._outgoing_high_water = high
|
| 856 |
+
self._outgoing_low_water = low
|
| 857 |
+
|
| 858 |
+
# Flow control for reads to APP socket
|
| 859 |
+
|
| 860 |
+
def _pause_reading(self):
|
| 861 |
+
self._app_reading_paused = True
|
| 862 |
+
|
| 863 |
+
def _resume_reading(self):
|
| 864 |
+
if self._app_reading_paused:
|
| 865 |
+
self._app_reading_paused = False
|
| 866 |
+
|
| 867 |
+
def resume():
|
| 868 |
+
if self._state == SSLProtocolState.WRAPPED:
|
| 869 |
+
self._do_read()
|
| 870 |
+
elif self._state == SSLProtocolState.FLUSHING:
|
| 871 |
+
self._do_flush()
|
| 872 |
+
elif self._state == SSLProtocolState.SHUTDOWN:
|
| 873 |
+
self._do_shutdown()
|
| 874 |
+
self._loop.call_soon(resume)
|
| 875 |
+
|
| 876 |
+
# Flow control for reads from SSL socket
|
| 877 |
+
|
| 878 |
+
def _control_ssl_reading(self):
|
| 879 |
+
size = self._get_read_buffer_size()
|
| 880 |
+
if size >= self._incoming_high_water and not self._ssl_reading_paused:
|
| 881 |
+
self._ssl_reading_paused = True
|
| 882 |
+
self._transport.pause_reading()
|
| 883 |
+
elif size <= self._incoming_low_water and self._ssl_reading_paused:
|
| 884 |
+
self._ssl_reading_paused = False
|
| 885 |
+
self._transport.resume_reading()
|
| 886 |
+
|
| 887 |
+
def _set_read_buffer_limits(self, high=None, low=None):
|
| 888 |
+
high, low = add_flowcontrol_defaults(
|
| 889 |
+
high, low, constants.FLOW_CONTROL_HIGH_WATER_SSL_READ)
|
| 890 |
+
self._incoming_high_water = high
|
| 891 |
+
self._incoming_low_water = low
|
| 892 |
+
|
| 893 |
+
def _get_read_buffer_size(self):
|
| 894 |
+
return self._incoming.pending
|
| 895 |
+
|
| 896 |
+
# Flow control for writes to SSL socket
|
| 897 |
+
|
| 898 |
+
def pause_writing(self):
|
| 899 |
+
"""Called when the low-level transport's buffer goes over
|
| 900 |
+
the high-water mark.
|
| 901 |
+
"""
|
| 902 |
+
assert not self._ssl_writing_paused
|
| 903 |
+
self._ssl_writing_paused = True
|
| 904 |
+
|
| 905 |
+
def resume_writing(self):
|
| 906 |
+
"""Called when the low-level transport's buffer drains below
|
| 907 |
+
the low-water mark.
|
| 908 |
+
"""
|
| 909 |
+
assert self._ssl_writing_paused
|
| 910 |
+
self._ssl_writing_paused = False
|
| 911 |
+
self._process_outgoing()
|
| 912 |
+
|
| 913 |
+
def _fatal_error(self, exc, message='Fatal error on transport'):
|
| 914 |
+
if self._transport:
|
| 915 |
+
self._transport._force_close(exc)
|
| 916 |
+
|
| 917 |
+
if isinstance(exc, OSError):
|
| 918 |
+
if self._loop.get_debug():
|
| 919 |
+
logger.debug("%r: %s", self, message, exc_info=True)
|
| 920 |
+
elif not isinstance(exc, exceptions.CancelledError):
|
| 921 |
+
self._loop.call_exception_handler({
|
| 922 |
+
'message': message,
|
| 923 |
+
'exception': exc,
|
| 924 |
+
'transport': self._transport,
|
| 925 |
+
'protocol': self,
|
| 926 |
+
})
|
micromamba_root/envs/pytorch_env/Lib/asyncio/staggered.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support for running coroutines in parallel with staggered start times."""
|
| 2 |
+
|
| 3 |
+
__all__ = 'staggered_race',
|
| 4 |
+
|
| 5 |
+
import contextlib
|
| 6 |
+
import typing
|
| 7 |
+
|
| 8 |
+
from . import events
|
| 9 |
+
from . import exceptions as exceptions_mod
|
| 10 |
+
from . import locks
|
| 11 |
+
from . import tasks
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
async def staggered_race(
|
| 15 |
+
coro_fns: typing.Iterable[typing.Callable[[], typing.Awaitable]],
|
| 16 |
+
delay: typing.Optional[float],
|
| 17 |
+
*,
|
| 18 |
+
loop: events.AbstractEventLoop = None,
|
| 19 |
+
) -> typing.Tuple[
|
| 20 |
+
typing.Any,
|
| 21 |
+
typing.Optional[int],
|
| 22 |
+
typing.List[typing.Optional[Exception]]
|
| 23 |
+
]:
|
| 24 |
+
"""Run coroutines with staggered start times and take the first to finish.
|
| 25 |
+
|
| 26 |
+
This method takes an iterable of coroutine functions. The first one is
|
| 27 |
+
started immediately. From then on, whenever the immediately preceding one
|
| 28 |
+
fails (raises an exception), or when *delay* seconds has passed, the next
|
| 29 |
+
coroutine is started. This continues until one of the coroutines complete
|
| 30 |
+
successfully, in which case all others are cancelled, or until all
|
| 31 |
+
coroutines fail.
|
| 32 |
+
|
| 33 |
+
The coroutines provided should be well-behaved in the following way:
|
| 34 |
+
|
| 35 |
+
* They should only ``return`` if completed successfully.
|
| 36 |
+
|
| 37 |
+
* They should always raise an exception if they did not complete
|
| 38 |
+
successfully. In particular, if they handle cancellation, they should
|
| 39 |
+
probably reraise, like this::
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
# do work
|
| 43 |
+
except asyncio.CancelledError:
|
| 44 |
+
# undo partially completed work
|
| 45 |
+
raise
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
coro_fns: an iterable of coroutine functions, i.e. callables that
|
| 49 |
+
return a coroutine object when called. Use ``functools.partial`` or
|
| 50 |
+
lambdas to pass arguments.
|
| 51 |
+
|
| 52 |
+
delay: amount of time, in seconds, between starting coroutines. If
|
| 53 |
+
``None``, the coroutines will run sequentially.
|
| 54 |
+
|
| 55 |
+
loop: the event loop to use.
|
| 56 |
+
|
| 57 |
+
Returns:
|
| 58 |
+
tuple *(winner_result, winner_index, exceptions)* where
|
| 59 |
+
|
| 60 |
+
- *winner_result*: the result of the winning coroutine, or ``None``
|
| 61 |
+
if no coroutines won.
|
| 62 |
+
|
| 63 |
+
- *winner_index*: the index of the winning coroutine in
|
| 64 |
+
``coro_fns``, or ``None`` if no coroutines won. If the winning
|
| 65 |
+
coroutine may return None on success, *winner_index* can be used
|
| 66 |
+
to definitively determine whether any coroutine won.
|
| 67 |
+
|
| 68 |
+
- *exceptions*: list of exceptions returned by the coroutines.
|
| 69 |
+
``len(exceptions)`` is equal to the number of coroutines actually
|
| 70 |
+
started, and the order is the same as in ``coro_fns``. The winning
|
| 71 |
+
coroutine's entry is ``None``.
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
# TODO: when we have aiter() and anext(), allow async iterables in coro_fns.
|
| 75 |
+
loop = loop or events.get_running_loop()
|
| 76 |
+
enum_coro_fns = enumerate(coro_fns)
|
| 77 |
+
winner_result = None
|
| 78 |
+
winner_index = None
|
| 79 |
+
exceptions = []
|
| 80 |
+
running_tasks = []
|
| 81 |
+
|
| 82 |
+
async def run_one_coro(
|
| 83 |
+
previous_failed: typing.Optional[locks.Event]) -> None:
|
| 84 |
+
# Wait for the previous task to finish, or for delay seconds
|
| 85 |
+
if previous_failed is not None:
|
| 86 |
+
with contextlib.suppress(exceptions_mod.TimeoutError):
|
| 87 |
+
# Use asyncio.wait_for() instead of asyncio.wait() here, so
|
| 88 |
+
# that if we get cancelled at this point, Event.wait() is also
|
| 89 |
+
# cancelled, otherwise there will be a "Task destroyed but it is
|
| 90 |
+
# pending" later.
|
| 91 |
+
await tasks.wait_for(previous_failed.wait(), delay)
|
| 92 |
+
# Get the next coroutine to run
|
| 93 |
+
try:
|
| 94 |
+
this_index, coro_fn = next(enum_coro_fns)
|
| 95 |
+
except StopIteration:
|
| 96 |
+
return
|
| 97 |
+
# Start task that will run the next coroutine
|
| 98 |
+
this_failed = locks.Event()
|
| 99 |
+
next_task = loop.create_task(run_one_coro(this_failed))
|
| 100 |
+
running_tasks.append(next_task)
|
| 101 |
+
assert len(running_tasks) == this_index + 2
|
| 102 |
+
# Prepare place to put this coroutine's exceptions if not won
|
| 103 |
+
exceptions.append(None)
|
| 104 |
+
assert len(exceptions) == this_index + 1
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
result = await coro_fn()
|
| 108 |
+
except (SystemExit, KeyboardInterrupt):
|
| 109 |
+
raise
|
| 110 |
+
except BaseException as e:
|
| 111 |
+
exceptions[this_index] = e
|
| 112 |
+
this_failed.set() # Kickstart the next coroutine
|
| 113 |
+
else:
|
| 114 |
+
# Store winner's results
|
| 115 |
+
nonlocal winner_index, winner_result
|
| 116 |
+
assert winner_index is None
|
| 117 |
+
winner_index = this_index
|
| 118 |
+
winner_result = result
|
| 119 |
+
# Cancel all other tasks. We take care to not cancel the current
|
| 120 |
+
# task as well. If we do so, then since there is no `await` after
|
| 121 |
+
# here and CancelledError are usually thrown at one, we will
|
| 122 |
+
# encounter a curious corner case where the current task will end
|
| 123 |
+
# up as done() == True, cancelled() == False, exception() ==
|
| 124 |
+
# asyncio.CancelledError. This behavior is specified in
|
| 125 |
+
# https://bugs.python.org/issue30048
|
| 126 |
+
for i, t in enumerate(running_tasks):
|
| 127 |
+
if i != this_index:
|
| 128 |
+
t.cancel()
|
| 129 |
+
|
| 130 |
+
first_task = loop.create_task(run_one_coro(None))
|
| 131 |
+
running_tasks.append(first_task)
|
| 132 |
+
try:
|
| 133 |
+
# Wait for a growing list of tasks to all finish: poor man's version of
|
| 134 |
+
# curio's TaskGroup or trio's nursery
|
| 135 |
+
done_count = 0
|
| 136 |
+
while done_count != len(running_tasks):
|
| 137 |
+
done, _ = await tasks.wait(running_tasks)
|
| 138 |
+
done_count = len(done)
|
| 139 |
+
# If run_one_coro raises an unhandled exception, it's probably a
|
| 140 |
+
# programming error, and I want to see it.
|
| 141 |
+
if __debug__:
|
| 142 |
+
for d in done:
|
| 143 |
+
if d.done() and not d.cancelled() and d.exception():
|
| 144 |
+
raise d.exception()
|
| 145 |
+
return winner_result, winner_index, exceptions
|
| 146 |
+
finally:
|
| 147 |
+
# Make sure no tasks are left running if we leave this function
|
| 148 |
+
for t in running_tasks:
|
| 149 |
+
t.cancel()
|
micromamba_root/envs/pytorch_env/Lib/asyncio/streams.py
ADDED
|
@@ -0,0 +1,768 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 7 |
+
import sys
|
| 8 |
+
import warnings
|
| 9 |
+
import weakref
|
| 10 |
+
|
| 11 |
+
if hasattr(socket, 'AF_UNIX'):
|
| 12 |
+
__all__ += ('open_unix_connection', 'start_unix_server')
|
| 13 |
+
|
| 14 |
+
from . import coroutines
|
| 15 |
+
from . import events
|
| 16 |
+
from . import exceptions
|
| 17 |
+
from . import format_helpers
|
| 18 |
+
from . import protocols
|
| 19 |
+
from .log import logger
|
| 20 |
+
from .tasks import sleep
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_DEFAULT_LIMIT = 2 ** 16 # 64 KiB
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
async def open_connection(host=None, port=None, *,
|
| 27 |
+
limit=_DEFAULT_LIMIT, **kwds):
|
| 28 |
+
"""A wrapper for create_connection() returning a (reader, writer) pair.
|
| 29 |
+
|
| 30 |
+
The reader returned is a StreamReader instance; the writer is a
|
| 31 |
+
StreamWriter instance.
|
| 32 |
+
|
| 33 |
+
The arguments are all the usual arguments to create_connection()
|
| 34 |
+
except protocol_factory; most common are positional host and port,
|
| 35 |
+
with various optional keyword arguments following.
|
| 36 |
+
|
| 37 |
+
Additional optional keyword arguments are loop (to set the event loop
|
| 38 |
+
instance to use) and limit (to set the buffer limit passed to the
|
| 39 |
+
StreamReader).
|
| 40 |
+
|
| 41 |
+
(If you want to customize the StreamReader and/or
|
| 42 |
+
StreamReaderProtocol classes, just copy the code -- there's
|
| 43 |
+
really nothing special here except some convenience.)
|
| 44 |
+
"""
|
| 45 |
+
loop = events.get_running_loop()
|
| 46 |
+
reader = StreamReader(limit=limit, loop=loop)
|
| 47 |
+
protocol = StreamReaderProtocol(reader, loop=loop)
|
| 48 |
+
transport, _ = await loop.create_connection(
|
| 49 |
+
lambda: protocol, host, port, **kwds)
|
| 50 |
+
writer = StreamWriter(transport, protocol, reader, loop)
|
| 51 |
+
return reader, writer
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
async def start_server(client_connected_cb, host=None, port=None, *,
|
| 55 |
+
limit=_DEFAULT_LIMIT, **kwds):
|
| 56 |
+
"""Start a socket server, call back for each client connected.
|
| 57 |
+
|
| 58 |
+
The first parameter, `client_connected_cb`, takes two parameters:
|
| 59 |
+
client_reader, client_writer. client_reader is a StreamReader
|
| 60 |
+
object, while client_writer is a StreamWriter object. This
|
| 61 |
+
parameter can either be a plain callback function or a coroutine;
|
| 62 |
+
if it is a coroutine, it will be automatically converted into a
|
| 63 |
+
Task.
|
| 64 |
+
|
| 65 |
+
The rest of the arguments are all the usual arguments to
|
| 66 |
+
loop.create_server() except protocol_factory; most common are
|
| 67 |
+
positional host and port, with various optional keyword arguments
|
| 68 |
+
following. The return value is the same as loop.create_server().
|
| 69 |
+
|
| 70 |
+
Additional optional keyword argument is limit (to set the buffer
|
| 71 |
+
limit passed to the StreamReader).
|
| 72 |
+
|
| 73 |
+
The return value is the same as loop.create_server(), i.e. a
|
| 74 |
+
Server object which can be used to stop the service.
|
| 75 |
+
"""
|
| 76 |
+
loop = events.get_running_loop()
|
| 77 |
+
|
| 78 |
+
def factory():
|
| 79 |
+
reader = StreamReader(limit=limit, loop=loop)
|
| 80 |
+
protocol = StreamReaderProtocol(reader, client_connected_cb,
|
| 81 |
+
loop=loop)
|
| 82 |
+
return protocol
|
| 83 |
+
|
| 84 |
+
return await loop.create_server(factory, host, port, **kwds)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if hasattr(socket, 'AF_UNIX'):
|
| 88 |
+
# UNIX Domain Sockets are supported on this platform
|
| 89 |
+
|
| 90 |
+
async def open_unix_connection(path=None, *,
|
| 91 |
+
limit=_DEFAULT_LIMIT, **kwds):
|
| 92 |
+
"""Similar to `open_connection` but works with UNIX Domain Sockets."""
|
| 93 |
+
loop = events.get_running_loop()
|
| 94 |
+
|
| 95 |
+
reader = StreamReader(limit=limit, loop=loop)
|
| 96 |
+
protocol = StreamReaderProtocol(reader, loop=loop)
|
| 97 |
+
transport, _ = await loop.create_unix_connection(
|
| 98 |
+
lambda: protocol, path, **kwds)
|
| 99 |
+
writer = StreamWriter(transport, protocol, reader, loop)
|
| 100 |
+
return reader, writer
|
| 101 |
+
|
| 102 |
+
async def start_unix_server(client_connected_cb, path=None, *,
|
| 103 |
+
limit=_DEFAULT_LIMIT, **kwds):
|
| 104 |
+
"""Similar to `start_server` but works with UNIX Domain Sockets."""
|
| 105 |
+
loop = events.get_running_loop()
|
| 106 |
+
|
| 107 |
+
def factory():
|
| 108 |
+
reader = StreamReader(limit=limit, loop=loop)
|
| 109 |
+
protocol = StreamReaderProtocol(reader, client_connected_cb,
|
| 110 |
+
loop=loop)
|
| 111 |
+
return protocol
|
| 112 |
+
|
| 113 |
+
return await loop.create_unix_server(factory, path, **kwds)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class FlowControlMixin(protocols.Protocol):
|
| 117 |
+
"""Reusable flow control logic for StreamWriter.drain().
|
| 118 |
+
|
| 119 |
+
This implements the protocol methods pause_writing(),
|
| 120 |
+
resume_writing() and connection_lost(). If the subclass overrides
|
| 121 |
+
these it must call the super methods.
|
| 122 |
+
|
| 123 |
+
StreamWriter.drain() must wait for _drain_helper() coroutine.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
def __init__(self, loop=None):
|
| 127 |
+
if loop is None:
|
| 128 |
+
self._loop = events._get_event_loop(stacklevel=4)
|
| 129 |
+
else:
|
| 130 |
+
self._loop = loop
|
| 131 |
+
self._paused = False
|
| 132 |
+
self._drain_waiters = collections.deque()
|
| 133 |
+
self._connection_lost = False
|
| 134 |
+
|
| 135 |
+
def pause_writing(self):
|
| 136 |
+
assert not self._paused
|
| 137 |
+
self._paused = True
|
| 138 |
+
if self._loop.get_debug():
|
| 139 |
+
logger.debug("%r pauses writing", self)
|
| 140 |
+
|
| 141 |
+
def resume_writing(self):
|
| 142 |
+
assert self._paused
|
| 143 |
+
self._paused = False
|
| 144 |
+
if self._loop.get_debug():
|
| 145 |
+
logger.debug("%r resumes writing", self)
|
| 146 |
+
|
| 147 |
+
for waiter in self._drain_waiters:
|
| 148 |
+
if not waiter.done():
|
| 149 |
+
waiter.set_result(None)
|
| 150 |
+
|
| 151 |
+
def connection_lost(self, exc):
|
| 152 |
+
self._connection_lost = True
|
| 153 |
+
# Wake up the writer(s) if currently paused.
|
| 154 |
+
if not self._paused:
|
| 155 |
+
return
|
| 156 |
+
|
| 157 |
+
for waiter in self._drain_waiters:
|
| 158 |
+
if not waiter.done():
|
| 159 |
+
if exc is None:
|
| 160 |
+
waiter.set_result(None)
|
| 161 |
+
else:
|
| 162 |
+
waiter.set_exception(exc)
|
| 163 |
+
|
| 164 |
+
async def _drain_helper(self):
|
| 165 |
+
if self._connection_lost:
|
| 166 |
+
raise ConnectionResetError('Connection lost')
|
| 167 |
+
if not self._paused:
|
| 168 |
+
return
|
| 169 |
+
waiter = self._loop.create_future()
|
| 170 |
+
self._drain_waiters.append(waiter)
|
| 171 |
+
try:
|
| 172 |
+
await waiter
|
| 173 |
+
finally:
|
| 174 |
+
self._drain_waiters.remove(waiter)
|
| 175 |
+
|
| 176 |
+
def _get_close_waiter(self, stream):
|
| 177 |
+
raise NotImplementedError
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class StreamReaderProtocol(FlowControlMixin, protocols.Protocol):
|
| 181 |
+
"""Helper class to adapt between Protocol and StreamReader.
|
| 182 |
+
|
| 183 |
+
(This is a helper class instead of making StreamReader itself a
|
| 184 |
+
Protocol subclass, because the StreamReader has other potential
|
| 185 |
+
uses, and to prevent the user of the StreamReader to accidentally
|
| 186 |
+
call inappropriate methods of the protocol.)
|
| 187 |
+
"""
|
| 188 |
+
|
| 189 |
+
_source_traceback = None
|
| 190 |
+
|
| 191 |
+
def __init__(self, stream_reader, client_connected_cb=None, loop=None):
|
| 192 |
+
super().__init__(loop=loop)
|
| 193 |
+
if stream_reader is not None:
|
| 194 |
+
self._stream_reader_wr = weakref.ref(stream_reader)
|
| 195 |
+
self._source_traceback = stream_reader._source_traceback
|
| 196 |
+
else:
|
| 197 |
+
self._stream_reader_wr = None
|
| 198 |
+
if client_connected_cb is not None:
|
| 199 |
+
# This is a stream created by the `create_server()` function.
|
| 200 |
+
# Keep a strong reference to the reader until a connection
|
| 201 |
+
# is established.
|
| 202 |
+
self._strong_reader = stream_reader
|
| 203 |
+
self._reject_connection = False
|
| 204 |
+
self._stream_writer = None
|
| 205 |
+
self._task = None
|
| 206 |
+
self._transport = None
|
| 207 |
+
self._client_connected_cb = client_connected_cb
|
| 208 |
+
self._over_ssl = False
|
| 209 |
+
self._closed = self._loop.create_future()
|
| 210 |
+
|
| 211 |
+
@property
|
| 212 |
+
def _stream_reader(self):
|
| 213 |
+
if self._stream_reader_wr is None:
|
| 214 |
+
return None
|
| 215 |
+
return self._stream_reader_wr()
|
| 216 |
+
|
| 217 |
+
def _replace_writer(self, writer):
|
| 218 |
+
loop = self._loop
|
| 219 |
+
transport = writer.transport
|
| 220 |
+
self._stream_writer = writer
|
| 221 |
+
self._transport = transport
|
| 222 |
+
self._over_ssl = transport.get_extra_info('sslcontext') is not None
|
| 223 |
+
|
| 224 |
+
def connection_made(self, transport):
|
| 225 |
+
if self._reject_connection:
|
| 226 |
+
context = {
|
| 227 |
+
'message': ('An open stream was garbage collected prior to '
|
| 228 |
+
'establishing network connection; '
|
| 229 |
+
'call "stream.close()" explicitly.')
|
| 230 |
+
}
|
| 231 |
+
if self._source_traceback:
|
| 232 |
+
context['source_traceback'] = self._source_traceback
|
| 233 |
+
self._loop.call_exception_handler(context)
|
| 234 |
+
transport.abort()
|
| 235 |
+
return
|
| 236 |
+
self._transport = transport
|
| 237 |
+
reader = self._stream_reader
|
| 238 |
+
if reader is not None:
|
| 239 |
+
reader.set_transport(transport)
|
| 240 |
+
self._over_ssl = transport.get_extra_info('sslcontext') is not None
|
| 241 |
+
if self._client_connected_cb is not None:
|
| 242 |
+
self._stream_writer = StreamWriter(transport, self,
|
| 243 |
+
reader,
|
| 244 |
+
self._loop)
|
| 245 |
+
res = self._client_connected_cb(reader,
|
| 246 |
+
self._stream_writer)
|
| 247 |
+
if coroutines.iscoroutine(res):
|
| 248 |
+
def callback(task):
|
| 249 |
+
if task.cancelled():
|
| 250 |
+
transport.close()
|
| 251 |
+
return
|
| 252 |
+
exc = task.exception()
|
| 253 |
+
if exc is not None:
|
| 254 |
+
self._loop.call_exception_handler({
|
| 255 |
+
'message': 'Unhandled exception in client_connected_cb',
|
| 256 |
+
'exception': exc,
|
| 257 |
+
'transport': transport,
|
| 258 |
+
})
|
| 259 |
+
transport.close()
|
| 260 |
+
|
| 261 |
+
self._task = self._loop.create_task(res)
|
| 262 |
+
self._task.add_done_callback(callback)
|
| 263 |
+
|
| 264 |
+
self._strong_reader = None
|
| 265 |
+
|
| 266 |
+
def connection_lost(self, exc):
|
| 267 |
+
reader = self._stream_reader
|
| 268 |
+
if reader is not None:
|
| 269 |
+
if exc is None:
|
| 270 |
+
reader.feed_eof()
|
| 271 |
+
else:
|
| 272 |
+
reader.set_exception(exc)
|
| 273 |
+
if not self._closed.done():
|
| 274 |
+
if exc is None:
|
| 275 |
+
self._closed.set_result(None)
|
| 276 |
+
else:
|
| 277 |
+
self._closed.set_exception(exc)
|
| 278 |
+
super().connection_lost(exc)
|
| 279 |
+
self._stream_reader_wr = None
|
| 280 |
+
self._stream_writer = None
|
| 281 |
+
self._task = None
|
| 282 |
+
self._transport = None
|
| 283 |
+
|
| 284 |
+
def data_received(self, data):
|
| 285 |
+
reader = self._stream_reader
|
| 286 |
+
if reader is not None:
|
| 287 |
+
reader.feed_data(data)
|
| 288 |
+
|
| 289 |
+
def eof_received(self):
|
| 290 |
+
reader = self._stream_reader
|
| 291 |
+
if reader is not None:
|
| 292 |
+
reader.feed_eof()
|
| 293 |
+
if self._over_ssl:
|
| 294 |
+
# Prevent a warning in SSLProtocol.eof_received:
|
| 295 |
+
# "returning true from eof_received()
|
| 296 |
+
# has no effect when using ssl"
|
| 297 |
+
return False
|
| 298 |
+
return True
|
| 299 |
+
|
| 300 |
+
def _get_close_waiter(self, stream):
|
| 301 |
+
return self._closed
|
| 302 |
+
|
| 303 |
+
def __del__(self):
|
| 304 |
+
# Prevent reports about unhandled exceptions.
|
| 305 |
+
# Better than self._closed._log_traceback = False hack
|
| 306 |
+
try:
|
| 307 |
+
closed = self._closed
|
| 308 |
+
except AttributeError:
|
| 309 |
+
pass # failed constructor
|
| 310 |
+
else:
|
| 311 |
+
if closed.done() and not closed.cancelled():
|
| 312 |
+
closed.exception()
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
class StreamWriter:
|
| 316 |
+
"""Wraps a Transport.
|
| 317 |
+
|
| 318 |
+
This exposes write(), writelines(), [can_]write_eof(),
|
| 319 |
+
get_extra_info() and close(). It adds drain() which returns an
|
| 320 |
+
optional Future on which you can wait for flow control. It also
|
| 321 |
+
adds a transport property which references the Transport
|
| 322 |
+
directly.
|
| 323 |
+
"""
|
| 324 |
+
|
| 325 |
+
def __init__(self, transport, protocol, reader, loop):
|
| 326 |
+
self._transport = transport
|
| 327 |
+
self._protocol = protocol
|
| 328 |
+
# drain() expects that the reader has an exception() method
|
| 329 |
+
assert reader is None or isinstance(reader, StreamReader)
|
| 330 |
+
self._reader = reader
|
| 331 |
+
self._loop = loop
|
| 332 |
+
self._complete_fut = self._loop.create_future()
|
| 333 |
+
self._complete_fut.set_result(None)
|
| 334 |
+
|
| 335 |
+
def __repr__(self):
|
| 336 |
+
info = [self.__class__.__name__, f'transport={self._transport!r}']
|
| 337 |
+
if self._reader is not None:
|
| 338 |
+
info.append(f'reader={self._reader!r}')
|
| 339 |
+
return '<{}>'.format(' '.join(info))
|
| 340 |
+
|
| 341 |
+
@property
|
| 342 |
+
def transport(self):
|
| 343 |
+
return self._transport
|
| 344 |
+
|
| 345 |
+
def write(self, data):
|
| 346 |
+
self._transport.write(data)
|
| 347 |
+
|
| 348 |
+
def writelines(self, data):
|
| 349 |
+
self._transport.writelines(data)
|
| 350 |
+
|
| 351 |
+
def write_eof(self):
|
| 352 |
+
return self._transport.write_eof()
|
| 353 |
+
|
| 354 |
+
def can_write_eof(self):
|
| 355 |
+
return self._transport.can_write_eof()
|
| 356 |
+
|
| 357 |
+
def close(self):
|
| 358 |
+
return self._transport.close()
|
| 359 |
+
|
| 360 |
+
def is_closing(self):
|
| 361 |
+
return self._transport.is_closing()
|
| 362 |
+
|
| 363 |
+
async def wait_closed(self):
|
| 364 |
+
await self._protocol._get_close_waiter(self)
|
| 365 |
+
|
| 366 |
+
def get_extra_info(self, name, default=None):
|
| 367 |
+
return self._transport.get_extra_info(name, default)
|
| 368 |
+
|
| 369 |
+
async def drain(self):
|
| 370 |
+
"""Flush the write buffer.
|
| 371 |
+
|
| 372 |
+
The intended use is to write
|
| 373 |
+
|
| 374 |
+
w.write(data)
|
| 375 |
+
await w.drain()
|
| 376 |
+
"""
|
| 377 |
+
if self._reader is not None:
|
| 378 |
+
exc = self._reader.exception()
|
| 379 |
+
if exc is not None:
|
| 380 |
+
raise exc
|
| 381 |
+
if self._transport.is_closing():
|
| 382 |
+
# Wait for protocol.connection_lost() call
|
| 383 |
+
# Raise connection closing error if any,
|
| 384 |
+
# ConnectionResetError otherwise
|
| 385 |
+
# Yield to the event loop so connection_lost() may be
|
| 386 |
+
# called. Without this, _drain_helper() would return
|
| 387 |
+
# immediately, and code that calls
|
| 388 |
+
# write(...); await drain()
|
| 389 |
+
# in a loop would never call connection_lost(), so it
|
| 390 |
+
# would not see an error when the socket is closed.
|
| 391 |
+
await sleep(0)
|
| 392 |
+
await self._protocol._drain_helper()
|
| 393 |
+
|
| 394 |
+
async def start_tls(self, sslcontext, *,
|
| 395 |
+
server_hostname=None,
|
| 396 |
+
ssl_handshake_timeout=None):
|
| 397 |
+
"""Upgrade an existing stream-based connection to TLS."""
|
| 398 |
+
server_side = self._protocol._client_connected_cb is not None
|
| 399 |
+
protocol = self._protocol
|
| 400 |
+
await self.drain()
|
| 401 |
+
new_transport = await self._loop.start_tls( # type: ignore
|
| 402 |
+
self._transport, protocol, sslcontext,
|
| 403 |
+
server_side=server_side, server_hostname=server_hostname,
|
| 404 |
+
ssl_handshake_timeout=ssl_handshake_timeout)
|
| 405 |
+
self._transport = new_transport
|
| 406 |
+
protocol._replace_writer(self)
|
| 407 |
+
|
| 408 |
+
def __del__(self):
|
| 409 |
+
if not self._transport.is_closing():
|
| 410 |
+
if self._loop.is_closed():
|
| 411 |
+
warnings.warn("loop is closed", ResourceWarning)
|
| 412 |
+
else:
|
| 413 |
+
self.close()
|
| 414 |
+
warnings.warn(f"unclosed {self!r}", ResourceWarning)
|
| 415 |
+
|
| 416 |
+
class StreamReader:
|
| 417 |
+
|
| 418 |
+
_source_traceback = None
|
| 419 |
+
|
| 420 |
+
def __init__(self, limit=_DEFAULT_LIMIT, loop=None):
|
| 421 |
+
# The line length limit is a security feature;
|
| 422 |
+
# it also doubles as half the buffer limit.
|
| 423 |
+
|
| 424 |
+
if limit <= 0:
|
| 425 |
+
raise ValueError('Limit cannot be <= 0')
|
| 426 |
+
|
| 427 |
+
self._limit = limit
|
| 428 |
+
if loop is None:
|
| 429 |
+
self._loop = events._get_event_loop()
|
| 430 |
+
else:
|
| 431 |
+
self._loop = loop
|
| 432 |
+
self._buffer = bytearray()
|
| 433 |
+
self._eof = False # Whether we're done.
|
| 434 |
+
self._waiter = None # A future used by _wait_for_data()
|
| 435 |
+
self._exception = None
|
| 436 |
+
self._transport = None
|
| 437 |
+
self._paused = False
|
| 438 |
+
if self._loop.get_debug():
|
| 439 |
+
self._source_traceback = format_helpers.extract_stack(
|
| 440 |
+
sys._getframe(1))
|
| 441 |
+
|
| 442 |
+
def __repr__(self):
|
| 443 |
+
info = ['StreamReader']
|
| 444 |
+
if self._buffer:
|
| 445 |
+
info.append(f'{len(self._buffer)} bytes')
|
| 446 |
+
if self._eof:
|
| 447 |
+
info.append('eof')
|
| 448 |
+
if self._limit != _DEFAULT_LIMIT:
|
| 449 |
+
info.append(f'limit={self._limit}')
|
| 450 |
+
if self._waiter:
|
| 451 |
+
info.append(f'waiter={self._waiter!r}')
|
| 452 |
+
if self._exception:
|
| 453 |
+
info.append(f'exception={self._exception!r}')
|
| 454 |
+
if self._transport:
|
| 455 |
+
info.append(f'transport={self._transport!r}')
|
| 456 |
+
if self._paused:
|
| 457 |
+
info.append('paused')
|
| 458 |
+
return '<{}>'.format(' '.join(info))
|
| 459 |
+
|
| 460 |
+
def exception(self):
|
| 461 |
+
return self._exception
|
| 462 |
+
|
| 463 |
+
def set_exception(self, exc):
|
| 464 |
+
self._exception = exc
|
| 465 |
+
|
| 466 |
+
waiter = self._waiter
|
| 467 |
+
if waiter is not None:
|
| 468 |
+
self._waiter = None
|
| 469 |
+
if not waiter.cancelled():
|
| 470 |
+
waiter.set_exception(exc)
|
| 471 |
+
|
| 472 |
+
def _wakeup_waiter(self):
|
| 473 |
+
"""Wakeup read*() functions waiting for data or EOF."""
|
| 474 |
+
waiter = self._waiter
|
| 475 |
+
if waiter is not None:
|
| 476 |
+
self._waiter = None
|
| 477 |
+
if not waiter.cancelled():
|
| 478 |
+
waiter.set_result(None)
|
| 479 |
+
|
| 480 |
+
def set_transport(self, transport):
|
| 481 |
+
assert self._transport is None, 'Transport already set'
|
| 482 |
+
self._transport = transport
|
| 483 |
+
|
| 484 |
+
def _maybe_resume_transport(self):
|
| 485 |
+
if self._paused and len(self._buffer) <= self._limit:
|
| 486 |
+
self._paused = False
|
| 487 |
+
self._transport.resume_reading()
|
| 488 |
+
|
| 489 |
+
def feed_eof(self):
|
| 490 |
+
self._eof = True
|
| 491 |
+
self._wakeup_waiter()
|
| 492 |
+
|
| 493 |
+
def at_eof(self):
|
| 494 |
+
"""Return True if the buffer is empty and 'feed_eof' was called."""
|
| 495 |
+
return self._eof and not self._buffer
|
| 496 |
+
|
| 497 |
+
def feed_data(self, data):
|
| 498 |
+
assert not self._eof, 'feed_data after feed_eof'
|
| 499 |
+
|
| 500 |
+
if not data:
|
| 501 |
+
return
|
| 502 |
+
|
| 503 |
+
self._buffer.extend(data)
|
| 504 |
+
self._wakeup_waiter()
|
| 505 |
+
|
| 506 |
+
if (self._transport is not None and
|
| 507 |
+
not self._paused and
|
| 508 |
+
len(self._buffer) > 2 * self._limit):
|
| 509 |
+
try:
|
| 510 |
+
self._transport.pause_reading()
|
| 511 |
+
except NotImplementedError:
|
| 512 |
+
# The transport can't be paused.
|
| 513 |
+
# We'll just have to buffer all data.
|
| 514 |
+
# Forget the transport so we don't keep trying.
|
| 515 |
+
self._transport = None
|
| 516 |
+
else:
|
| 517 |
+
self._paused = True
|
| 518 |
+
|
| 519 |
+
async def _wait_for_data(self, func_name):
|
| 520 |
+
"""Wait until feed_data() or feed_eof() is called.
|
| 521 |
+
|
| 522 |
+
If stream was paused, automatically resume it.
|
| 523 |
+
"""
|
| 524 |
+
# StreamReader uses a future to link the protocol feed_data() method
|
| 525 |
+
# to a read coroutine. Running two read coroutines at the same time
|
| 526 |
+
# would have an unexpected behaviour. It would not possible to know
|
| 527 |
+
# which coroutine would get the next data.
|
| 528 |
+
if self._waiter is not None:
|
| 529 |
+
raise RuntimeError(
|
| 530 |
+
f'{func_name}() called while another coroutine is '
|
| 531 |
+
f'already waiting for incoming data')
|
| 532 |
+
|
| 533 |
+
assert not self._eof, '_wait_for_data after EOF'
|
| 534 |
+
|
| 535 |
+
# Waiting for data while paused will make deadlock, so prevent it.
|
| 536 |
+
# This is essential for readexactly(n) for case when n > self._limit.
|
| 537 |
+
if self._paused:
|
| 538 |
+
self._paused = False
|
| 539 |
+
self._transport.resume_reading()
|
| 540 |
+
|
| 541 |
+
self._waiter = self._loop.create_future()
|
| 542 |
+
try:
|
| 543 |
+
await self._waiter
|
| 544 |
+
finally:
|
| 545 |
+
self._waiter = None
|
| 546 |
+
|
| 547 |
+
async def readline(self):
|
| 548 |
+
"""Read chunk of data from the stream until newline (b'\n') is found.
|
| 549 |
+
|
| 550 |
+
On success, return chunk that ends with newline. If only partial
|
| 551 |
+
line can be read due to EOF, return incomplete line without
|
| 552 |
+
terminating newline. When EOF was reached while no bytes read, empty
|
| 553 |
+
bytes object is returned.
|
| 554 |
+
|
| 555 |
+
If limit is reached, ValueError will be raised. In that case, if
|
| 556 |
+
newline was found, complete line including newline will be removed
|
| 557 |
+
from internal buffer. Else, internal buffer will be cleared. Limit is
|
| 558 |
+
compared against part of the line without newline.
|
| 559 |
+
|
| 560 |
+
If stream was paused, this function will automatically resume it if
|
| 561 |
+
needed.
|
| 562 |
+
"""
|
| 563 |
+
sep = b'\n'
|
| 564 |
+
seplen = len(sep)
|
| 565 |
+
try:
|
| 566 |
+
line = await self.readuntil(sep)
|
| 567 |
+
except exceptions.IncompleteReadError as e:
|
| 568 |
+
return e.partial
|
| 569 |
+
except exceptions.LimitOverrunError as e:
|
| 570 |
+
if self._buffer.startswith(sep, e.consumed):
|
| 571 |
+
del self._buffer[:e.consumed + seplen]
|
| 572 |
+
else:
|
| 573 |
+
self._buffer.clear()
|
| 574 |
+
self._maybe_resume_transport()
|
| 575 |
+
raise ValueError(e.args[0])
|
| 576 |
+
return line
|
| 577 |
+
|
| 578 |
+
async def readuntil(self, separator=b'\n'):
|
| 579 |
+
"""Read data from the stream until ``separator`` is found.
|
| 580 |
+
|
| 581 |
+
On success, the data and separator will be removed from the
|
| 582 |
+
internal buffer (consumed). Returned data will include the
|
| 583 |
+
separator at the end.
|
| 584 |
+
|
| 585 |
+
Configured stream limit is used to check result. Limit sets the
|
| 586 |
+
maximal length of data that can be returned, not counting the
|
| 587 |
+
separator.
|
| 588 |
+
|
| 589 |
+
If an EOF occurs and the complete separator is still not found,
|
| 590 |
+
an IncompleteReadError exception will be raised, and the internal
|
| 591 |
+
buffer will be reset. The IncompleteReadError.partial attribute
|
| 592 |
+
may contain the separator partially.
|
| 593 |
+
|
| 594 |
+
If the data cannot be read because of over limit, a
|
| 595 |
+
LimitOverrunError exception will be raised, and the data
|
| 596 |
+
will be left in the internal buffer, so it can be read again.
|
| 597 |
+
"""
|
| 598 |
+
seplen = len(separator)
|
| 599 |
+
if seplen == 0:
|
| 600 |
+
raise ValueError('Separator should be at least one-byte string')
|
| 601 |
+
|
| 602 |
+
if self._exception is not None:
|
| 603 |
+
raise self._exception
|
| 604 |
+
|
| 605 |
+
# Consume whole buffer except last bytes, which length is
|
| 606 |
+
# one less than seplen. Let's check corner cases with
|
| 607 |
+
# separator='SEPARATOR':
|
| 608 |
+
# * we have received almost complete separator (without last
|
| 609 |
+
# byte). i.e buffer='some textSEPARATO'. In this case we
|
| 610 |
+
# can safely consume len(separator) - 1 bytes.
|
| 611 |
+
# * last byte of buffer is first byte of separator, i.e.
|
| 612 |
+
# buffer='abcdefghijklmnopqrS'. We may safely consume
|
| 613 |
+
# everything except that last byte, but this require to
|
| 614 |
+
# analyze bytes of buffer that match partial separator.
|
| 615 |
+
# This is slow and/or require FSM. For this case our
|
| 616 |
+
# implementation is not optimal, since require rescanning
|
| 617 |
+
# of data that is known to not belong to separator. In
|
| 618 |
+
# real world, separator will not be so long to notice
|
| 619 |
+
# performance problems. Even when reading MIME-encoded
|
| 620 |
+
# messages :)
|
| 621 |
+
|
| 622 |
+
# `offset` is the number of bytes from the beginning of the buffer
|
| 623 |
+
# where there is no occurrence of `separator`.
|
| 624 |
+
offset = 0
|
| 625 |
+
|
| 626 |
+
# Loop until we find `separator` in the buffer, exceed the buffer size,
|
| 627 |
+
# or an EOF has happened.
|
| 628 |
+
while True:
|
| 629 |
+
buflen = len(self._buffer)
|
| 630 |
+
|
| 631 |
+
# Check if we now have enough data in the buffer for `separator` to
|
| 632 |
+
# fit.
|
| 633 |
+
if buflen - offset >= seplen:
|
| 634 |
+
isep = self._buffer.find(separator, offset)
|
| 635 |
+
|
| 636 |
+
if isep != -1:
|
| 637 |
+
# `separator` is in the buffer. `isep` will be used later
|
| 638 |
+
# to retrieve the data.
|
| 639 |
+
break
|
| 640 |
+
|
| 641 |
+
# see upper comment for explanation.
|
| 642 |
+
offset = buflen + 1 - seplen
|
| 643 |
+
if offset > self._limit:
|
| 644 |
+
raise exceptions.LimitOverrunError(
|
| 645 |
+
'Separator is not found, and chunk exceed the limit',
|
| 646 |
+
offset)
|
| 647 |
+
|
| 648 |
+
# Complete message (with full separator) may be present in buffer
|
| 649 |
+
# even when EOF flag is set. This may happen when the last chunk
|
| 650 |
+
# adds data which makes separator be found. That's why we check for
|
| 651 |
+
# EOF *ater* inspecting the buffer.
|
| 652 |
+
if self._eof:
|
| 653 |
+
chunk = bytes(self._buffer)
|
| 654 |
+
self._buffer.clear()
|
| 655 |
+
raise exceptions.IncompleteReadError(chunk, None)
|
| 656 |
+
|
| 657 |
+
# _wait_for_data() will resume reading if stream was paused.
|
| 658 |
+
await self._wait_for_data('readuntil')
|
| 659 |
+
|
| 660 |
+
if isep > self._limit:
|
| 661 |
+
raise exceptions.LimitOverrunError(
|
| 662 |
+
'Separator is found, but chunk is longer than limit', isep)
|
| 663 |
+
|
| 664 |
+
chunk = self._buffer[:isep + seplen]
|
| 665 |
+
del self._buffer[:isep + seplen]
|
| 666 |
+
self._maybe_resume_transport()
|
| 667 |
+
return bytes(chunk)
|
| 668 |
+
|
| 669 |
+
async def read(self, n=-1):
|
| 670 |
+
"""Read up to `n` bytes from the stream.
|
| 671 |
+
|
| 672 |
+
If `n` is not provided or set to -1,
|
| 673 |
+
read until EOF, then return all read bytes.
|
| 674 |
+
If EOF was received and the internal buffer is empty,
|
| 675 |
+
return an empty bytes object.
|
| 676 |
+
|
| 677 |
+
If `n` is 0, return an empty bytes object immediately.
|
| 678 |
+
|
| 679 |
+
If `n` is positive, return at most `n` available bytes
|
| 680 |
+
as soon as at least 1 byte is available in the internal buffer.
|
| 681 |
+
If EOF is received before any byte is read, return an empty
|
| 682 |
+
bytes object.
|
| 683 |
+
|
| 684 |
+
Returned value is not limited with limit, configured at stream
|
| 685 |
+
creation.
|
| 686 |
+
|
| 687 |
+
If stream was paused, this function will automatically resume it if
|
| 688 |
+
needed.
|
| 689 |
+
"""
|
| 690 |
+
|
| 691 |
+
if self._exception is not None:
|
| 692 |
+
raise self._exception
|
| 693 |
+
|
| 694 |
+
if n == 0:
|
| 695 |
+
return b''
|
| 696 |
+
|
| 697 |
+
if n < 0:
|
| 698 |
+
# This used to just loop creating a new waiter hoping to
|
| 699 |
+
# collect everything in self._buffer, but that would
|
| 700 |
+
# deadlock if the subprocess sends more than self.limit
|
| 701 |
+
# bytes. So just call self.read(self._limit) until EOF.
|
| 702 |
+
blocks = []
|
| 703 |
+
while True:
|
| 704 |
+
block = await self.read(self._limit)
|
| 705 |
+
if not block:
|
| 706 |
+
break
|
| 707 |
+
blocks.append(block)
|
| 708 |
+
return b''.join(blocks)
|
| 709 |
+
|
| 710 |
+
if not self._buffer and not self._eof:
|
| 711 |
+
await self._wait_for_data('read')
|
| 712 |
+
|
| 713 |
+
# This will work right even if buffer is less than n bytes
|
| 714 |
+
data = bytes(self._buffer[:n])
|
| 715 |
+
del self._buffer[:n]
|
| 716 |
+
|
| 717 |
+
self._maybe_resume_transport()
|
| 718 |
+
return data
|
| 719 |
+
|
| 720 |
+
async def readexactly(self, n):
|
| 721 |
+
"""Read exactly `n` bytes.
|
| 722 |
+
|
| 723 |
+
Raise an IncompleteReadError if EOF is reached before `n` bytes can be
|
| 724 |
+
read. The IncompleteReadError.partial attribute of the exception will
|
| 725 |
+
contain the partial read bytes.
|
| 726 |
+
|
| 727 |
+
if n is zero, return empty bytes object.
|
| 728 |
+
|
| 729 |
+
Returned value is not limited with limit, configured at stream
|
| 730 |
+
creation.
|
| 731 |
+
|
| 732 |
+
If stream was paused, this function will automatically resume it if
|
| 733 |
+
needed.
|
| 734 |
+
"""
|
| 735 |
+
if n < 0:
|
| 736 |
+
raise ValueError('readexactly size can not be less than zero')
|
| 737 |
+
|
| 738 |
+
if self._exception is not None:
|
| 739 |
+
raise self._exception
|
| 740 |
+
|
| 741 |
+
if n == 0:
|
| 742 |
+
return b''
|
| 743 |
+
|
| 744 |
+
while len(self._buffer) < n:
|
| 745 |
+
if self._eof:
|
| 746 |
+
incomplete = bytes(self._buffer)
|
| 747 |
+
self._buffer.clear()
|
| 748 |
+
raise exceptions.IncompleteReadError(incomplete, n)
|
| 749 |
+
|
| 750 |
+
await self._wait_for_data('readexactly')
|
| 751 |
+
|
| 752 |
+
if len(self._buffer) == n:
|
| 753 |
+
data = bytes(self._buffer)
|
| 754 |
+
self._buffer.clear()
|
| 755 |
+
else:
|
| 756 |
+
data = bytes(self._buffer[:n])
|
| 757 |
+
del self._buffer[:n]
|
| 758 |
+
self._maybe_resume_transport()
|
| 759 |
+
return data
|
| 760 |
+
|
| 761 |
+
def __aiter__(self):
|
| 762 |
+
return self
|
| 763 |
+
|
| 764 |
+
async def __anext__(self):
|
| 765 |
+
val = await self.readline()
|
| 766 |
+
if val == b'':
|
| 767 |
+
raise StopAsyncIteration
|
| 768 |
+
return val
|
micromamba_root/envs/pytorch_env/Lib/asyncio/subprocess.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__all__ = 'create_subprocess_exec', 'create_subprocess_shell'
|
| 2 |
+
|
| 3 |
+
import subprocess
|
| 4 |
+
|
| 5 |
+
from . import events
|
| 6 |
+
from . import protocols
|
| 7 |
+
from . import streams
|
| 8 |
+
from . import tasks
|
| 9 |
+
from .log import logger
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
PIPE = subprocess.PIPE
|
| 13 |
+
STDOUT = subprocess.STDOUT
|
| 14 |
+
DEVNULL = subprocess.DEVNULL
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class SubprocessStreamProtocol(streams.FlowControlMixin,
|
| 18 |
+
protocols.SubprocessProtocol):
|
| 19 |
+
"""Like StreamReaderProtocol, but for a subprocess."""
|
| 20 |
+
|
| 21 |
+
def __init__(self, limit, loop):
|
| 22 |
+
super().__init__(loop=loop)
|
| 23 |
+
self._limit = limit
|
| 24 |
+
self.stdin = self.stdout = self.stderr = None
|
| 25 |
+
self._transport = None
|
| 26 |
+
self._process_exited = False
|
| 27 |
+
self._pipe_fds = []
|
| 28 |
+
self._stdin_closed = self._loop.create_future()
|
| 29 |
+
|
| 30 |
+
def __repr__(self):
|
| 31 |
+
info = [self.__class__.__name__]
|
| 32 |
+
if self.stdin is not None:
|
| 33 |
+
info.append(f'stdin={self.stdin!r}')
|
| 34 |
+
if self.stdout is not None:
|
| 35 |
+
info.append(f'stdout={self.stdout!r}')
|
| 36 |
+
if self.stderr is not None:
|
| 37 |
+
info.append(f'stderr={self.stderr!r}')
|
| 38 |
+
return '<{}>'.format(' '.join(info))
|
| 39 |
+
|
| 40 |
+
def connection_made(self, transport):
|
| 41 |
+
self._transport = transport
|
| 42 |
+
|
| 43 |
+
stdout_transport = transport.get_pipe_transport(1)
|
| 44 |
+
if stdout_transport is not None:
|
| 45 |
+
self.stdout = streams.StreamReader(limit=self._limit,
|
| 46 |
+
loop=self._loop)
|
| 47 |
+
self.stdout.set_transport(stdout_transport)
|
| 48 |
+
self._pipe_fds.append(1)
|
| 49 |
+
|
| 50 |
+
stderr_transport = transport.get_pipe_transport(2)
|
| 51 |
+
if stderr_transport is not None:
|
| 52 |
+
self.stderr = streams.StreamReader(limit=self._limit,
|
| 53 |
+
loop=self._loop)
|
| 54 |
+
self.stderr.set_transport(stderr_transport)
|
| 55 |
+
self._pipe_fds.append(2)
|
| 56 |
+
|
| 57 |
+
stdin_transport = transport.get_pipe_transport(0)
|
| 58 |
+
if stdin_transport is not None:
|
| 59 |
+
self.stdin = streams.StreamWriter(stdin_transport,
|
| 60 |
+
protocol=self,
|
| 61 |
+
reader=None,
|
| 62 |
+
loop=self._loop)
|
| 63 |
+
|
| 64 |
+
def pipe_data_received(self, fd, data):
|
| 65 |
+
if fd == 1:
|
| 66 |
+
reader = self.stdout
|
| 67 |
+
elif fd == 2:
|
| 68 |
+
reader = self.stderr
|
| 69 |
+
else:
|
| 70 |
+
reader = None
|
| 71 |
+
if reader is not None:
|
| 72 |
+
reader.feed_data(data)
|
| 73 |
+
|
| 74 |
+
def pipe_connection_lost(self, fd, exc):
|
| 75 |
+
if fd == 0:
|
| 76 |
+
pipe = self.stdin
|
| 77 |
+
if pipe is not None:
|
| 78 |
+
pipe.close()
|
| 79 |
+
self.connection_lost(exc)
|
| 80 |
+
if exc is None:
|
| 81 |
+
self._stdin_closed.set_result(None)
|
| 82 |
+
else:
|
| 83 |
+
self._stdin_closed.set_exception(exc)
|
| 84 |
+
# Since calling `wait_closed()` is not mandatory,
|
| 85 |
+
# we shouldn't log the traceback if this is not awaited.
|
| 86 |
+
self._stdin_closed._log_traceback = False
|
| 87 |
+
return
|
| 88 |
+
if fd == 1:
|
| 89 |
+
reader = self.stdout
|
| 90 |
+
elif fd == 2:
|
| 91 |
+
reader = self.stderr
|
| 92 |
+
else:
|
| 93 |
+
reader = None
|
| 94 |
+
if reader is not None:
|
| 95 |
+
if exc is None:
|
| 96 |
+
reader.feed_eof()
|
| 97 |
+
else:
|
| 98 |
+
reader.set_exception(exc)
|
| 99 |
+
|
| 100 |
+
if fd in self._pipe_fds:
|
| 101 |
+
self._pipe_fds.remove(fd)
|
| 102 |
+
self._maybe_close_transport()
|
| 103 |
+
|
| 104 |
+
def process_exited(self):
|
| 105 |
+
self._process_exited = True
|
| 106 |
+
self._maybe_close_transport()
|
| 107 |
+
|
| 108 |
+
def _maybe_close_transport(self):
|
| 109 |
+
if len(self._pipe_fds) == 0 and self._process_exited:
|
| 110 |
+
self._transport.close()
|
| 111 |
+
self._transport = None
|
| 112 |
+
|
| 113 |
+
def _get_close_waiter(self, stream):
|
| 114 |
+
if stream is self.stdin:
|
| 115 |
+
return self._stdin_closed
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class Process:
|
| 119 |
+
def __init__(self, transport, protocol, loop):
|
| 120 |
+
self._transport = transport
|
| 121 |
+
self._protocol = protocol
|
| 122 |
+
self._loop = loop
|
| 123 |
+
self.stdin = protocol.stdin
|
| 124 |
+
self.stdout = protocol.stdout
|
| 125 |
+
self.stderr = protocol.stderr
|
| 126 |
+
self.pid = transport.get_pid()
|
| 127 |
+
|
| 128 |
+
def __repr__(self):
|
| 129 |
+
return f'<{self.__class__.__name__} {self.pid}>'
|
| 130 |
+
|
| 131 |
+
@property
|
| 132 |
+
def returncode(self):
|
| 133 |
+
return self._transport.get_returncode()
|
| 134 |
+
|
| 135 |
+
async def wait(self):
|
| 136 |
+
"""Wait until the process exit and return the process return code."""
|
| 137 |
+
return await self._transport._wait()
|
| 138 |
+
|
| 139 |
+
def send_signal(self, signal):
|
| 140 |
+
self._transport.send_signal(signal)
|
| 141 |
+
|
| 142 |
+
def terminate(self):
|
| 143 |
+
self._transport.terminate()
|
| 144 |
+
|
| 145 |
+
def kill(self):
|
| 146 |
+
self._transport.kill()
|
| 147 |
+
|
| 148 |
+
async def _feed_stdin(self, input):
|
| 149 |
+
debug = self._loop.get_debug()
|
| 150 |
+
try:
|
| 151 |
+
self.stdin.write(input)
|
| 152 |
+
if debug:
|
| 153 |
+
logger.debug(
|
| 154 |
+
'%r communicate: feed stdin (%s bytes)', self, len(input))
|
| 155 |
+
|
| 156 |
+
await self.stdin.drain()
|
| 157 |
+
except (BrokenPipeError, ConnectionResetError) as exc:
|
| 158 |
+
# communicate() ignores BrokenPipeError and ConnectionResetError.
|
| 159 |
+
# write() and drain() can raise these exceptions.
|
| 160 |
+
if debug:
|
| 161 |
+
logger.debug('%r communicate: stdin got %r', self, exc)
|
| 162 |
+
|
| 163 |
+
if debug:
|
| 164 |
+
logger.debug('%r communicate: close stdin', self)
|
| 165 |
+
self.stdin.close()
|
| 166 |
+
|
| 167 |
+
async def _noop(self):
|
| 168 |
+
return None
|
| 169 |
+
|
| 170 |
+
async def _read_stream(self, fd):
|
| 171 |
+
transport = self._transport.get_pipe_transport(fd)
|
| 172 |
+
if fd == 2:
|
| 173 |
+
stream = self.stderr
|
| 174 |
+
else:
|
| 175 |
+
assert fd == 1
|
| 176 |
+
stream = self.stdout
|
| 177 |
+
if self._loop.get_debug():
|
| 178 |
+
name = 'stdout' if fd == 1 else 'stderr'
|
| 179 |
+
logger.debug('%r communicate: read %s', self, name)
|
| 180 |
+
output = await stream.read()
|
| 181 |
+
if self._loop.get_debug():
|
| 182 |
+
name = 'stdout' if fd == 1 else 'stderr'
|
| 183 |
+
logger.debug('%r communicate: close %s', self, name)
|
| 184 |
+
transport.close()
|
| 185 |
+
return output
|
| 186 |
+
|
| 187 |
+
async def communicate(self, input=None):
|
| 188 |
+
if input is not None:
|
| 189 |
+
stdin = self._feed_stdin(input)
|
| 190 |
+
else:
|
| 191 |
+
stdin = self._noop()
|
| 192 |
+
if self.stdout is not None:
|
| 193 |
+
stdout = self._read_stream(1)
|
| 194 |
+
else:
|
| 195 |
+
stdout = self._noop()
|
| 196 |
+
if self.stderr is not None:
|
| 197 |
+
stderr = self._read_stream(2)
|
| 198 |
+
else:
|
| 199 |
+
stderr = self._noop()
|
| 200 |
+
stdin, stdout, stderr = await tasks.gather(stdin, stdout, stderr)
|
| 201 |
+
await self.wait()
|
| 202 |
+
return (stdout, stderr)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
async def create_subprocess_shell(cmd, stdin=None, stdout=None, stderr=None,
|
| 206 |
+
limit=streams._DEFAULT_LIMIT, **kwds):
|
| 207 |
+
loop = events.get_running_loop()
|
| 208 |
+
protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
|
| 209 |
+
loop=loop)
|
| 210 |
+
transport, protocol = await loop.subprocess_shell(
|
| 211 |
+
protocol_factory,
|
| 212 |
+
cmd, stdin=stdin, stdout=stdout,
|
| 213 |
+
stderr=stderr, **kwds)
|
| 214 |
+
return Process(transport, protocol, loop)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
async def create_subprocess_exec(program, *args, stdin=None, stdout=None,
|
| 218 |
+
stderr=None, limit=streams._DEFAULT_LIMIT,
|
| 219 |
+
**kwds):
|
| 220 |
+
loop = events.get_running_loop()
|
| 221 |
+
protocol_factory = lambda: SubprocessStreamProtocol(limit=limit,
|
| 222 |
+
loop=loop)
|
| 223 |
+
transport, protocol = await loop.subprocess_exec(
|
| 224 |
+
protocol_factory,
|
| 225 |
+
program, *args,
|
| 226 |
+
stdin=stdin, stdout=stdout,
|
| 227 |
+
stderr=stderr, **kwds)
|
| 228 |
+
return Process(transport, protocol, loop)
|
micromamba_root/envs/pytorch_env/Lib/asyncio/taskgroups.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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tasks
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TaskGroup:
|
| 13 |
+
"""Asynchronous context manager for managing groups of tasks.
|
| 14 |
+
|
| 15 |
+
Example use:
|
| 16 |
+
|
| 17 |
+
async with asyncio.TaskGroup() as group:
|
| 18 |
+
task1 = group.create_task(some_coroutine(...))
|
| 19 |
+
task2 = group.create_task(other_coroutine(...))
|
| 20 |
+
print("Both tasks have completed now.")
|
| 21 |
+
|
| 22 |
+
All tasks are awaited when the context manager exits.
|
| 23 |
+
|
| 24 |
+
Any exceptions other than `asyncio.CancelledError` raised within
|
| 25 |
+
a task will cancel all remaining tasks and wait for them to exit.
|
| 26 |
+
The exceptions are then combined and raised as an `ExceptionGroup`.
|
| 27 |
+
"""
|
| 28 |
+
def __init__(self):
|
| 29 |
+
self._entered = False
|
| 30 |
+
self._exiting = False
|
| 31 |
+
self._aborting = False
|
| 32 |
+
self._loop = None
|
| 33 |
+
self._parent_task = None
|
| 34 |
+
self._parent_cancel_requested = False
|
| 35 |
+
self._tasks = set()
|
| 36 |
+
self._errors = []
|
| 37 |
+
self._base_error = None
|
| 38 |
+
self._on_completed_fut = None
|
| 39 |
+
|
| 40 |
+
def __repr__(self):
|
| 41 |
+
info = ['']
|
| 42 |
+
if self._tasks:
|
| 43 |
+
info.append(f'tasks={len(self._tasks)}')
|
| 44 |
+
if self._errors:
|
| 45 |
+
info.append(f'errors={len(self._errors)}')
|
| 46 |
+
if self._aborting:
|
| 47 |
+
info.append('cancelling')
|
| 48 |
+
elif self._entered:
|
| 49 |
+
info.append('entered')
|
| 50 |
+
|
| 51 |
+
info_str = ' '.join(info)
|
| 52 |
+
return f'<TaskGroup{info_str}>'
|
| 53 |
+
|
| 54 |
+
async def __aenter__(self):
|
| 55 |
+
if self._entered:
|
| 56 |
+
raise RuntimeError(
|
| 57 |
+
f"TaskGroup {self!r} has already been entered")
|
| 58 |
+
if self._loop is None:
|
| 59 |
+
self._loop = events.get_running_loop()
|
| 60 |
+
self._parent_task = tasks.current_task(self._loop)
|
| 61 |
+
if self._parent_task is None:
|
| 62 |
+
raise RuntimeError(
|
| 63 |
+
f'TaskGroup {self!r} cannot determine the parent task')
|
| 64 |
+
self._entered = True
|
| 65 |
+
|
| 66 |
+
return self
|
| 67 |
+
|
| 68 |
+
async def __aexit__(self, et, exc, tb):
|
| 69 |
+
self._exiting = True
|
| 70 |
+
|
| 71 |
+
if (exc is not None and
|
| 72 |
+
self._is_base_error(exc) and
|
| 73 |
+
self._base_error is None):
|
| 74 |
+
self._base_error = exc
|
| 75 |
+
|
| 76 |
+
propagate_cancellation_error = \
|
| 77 |
+
exc if et is exceptions.CancelledError else None
|
| 78 |
+
if self._parent_cancel_requested:
|
| 79 |
+
# If this flag is set we *must* call uncancel().
|
| 80 |
+
if self._parent_task.uncancel() == 0:
|
| 81 |
+
# If there are no pending cancellations left,
|
| 82 |
+
# don't propagate CancelledError.
|
| 83 |
+
propagate_cancellation_error = None
|
| 84 |
+
|
| 85 |
+
if et is not None:
|
| 86 |
+
if not self._aborting:
|
| 87 |
+
# Our parent task is being cancelled:
|
| 88 |
+
#
|
| 89 |
+
# async with TaskGroup() as g:
|
| 90 |
+
# g.create_task(...)
|
| 91 |
+
# await ... # <- CancelledError
|
| 92 |
+
#
|
| 93 |
+
# or there's an exception in "async with":
|
| 94 |
+
#
|
| 95 |
+
# async with TaskGroup() as g:
|
| 96 |
+
# g.create_task(...)
|
| 97 |
+
# 1 / 0
|
| 98 |
+
#
|
| 99 |
+
self._abort()
|
| 100 |
+
|
| 101 |
+
# We use while-loop here because "self._on_completed_fut"
|
| 102 |
+
# can be cancelled multiple times if our parent task
|
| 103 |
+
# is being cancelled repeatedly (or even once, when
|
| 104 |
+
# our own cancellation is already in progress)
|
| 105 |
+
while self._tasks:
|
| 106 |
+
if self._on_completed_fut is None:
|
| 107 |
+
self._on_completed_fut = self._loop.create_future()
|
| 108 |
+
|
| 109 |
+
try:
|
| 110 |
+
await self._on_completed_fut
|
| 111 |
+
except exceptions.CancelledError as ex:
|
| 112 |
+
if not self._aborting:
|
| 113 |
+
# Our parent task is being cancelled:
|
| 114 |
+
#
|
| 115 |
+
# async def wrapper():
|
| 116 |
+
# async with TaskGroup() as g:
|
| 117 |
+
# g.create_task(foo)
|
| 118 |
+
#
|
| 119 |
+
# "wrapper" is being cancelled while "foo" is
|
| 120 |
+
# still running.
|
| 121 |
+
propagate_cancellation_error = ex
|
| 122 |
+
self._abort()
|
| 123 |
+
|
| 124 |
+
self._on_completed_fut = None
|
| 125 |
+
|
| 126 |
+
assert not self._tasks
|
| 127 |
+
|
| 128 |
+
if self._base_error is not None:
|
| 129 |
+
raise self._base_error
|
| 130 |
+
|
| 131 |
+
# Propagate CancelledError if there is one, except if there
|
| 132 |
+
# are other errors -- those have priority.
|
| 133 |
+
if propagate_cancellation_error and not self._errors:
|
| 134 |
+
raise propagate_cancellation_error
|
| 135 |
+
|
| 136 |
+
if et is not None and et is not exceptions.CancelledError:
|
| 137 |
+
self._errors.append(exc)
|
| 138 |
+
|
| 139 |
+
if self._errors:
|
| 140 |
+
# Exceptions are heavy objects that can have object
|
| 141 |
+
# cycles (bad for GC); let's not keep a reference to
|
| 142 |
+
# a bunch of them.
|
| 143 |
+
try:
|
| 144 |
+
me = BaseExceptionGroup('unhandled errors in a TaskGroup', self._errors)
|
| 145 |
+
raise me from None
|
| 146 |
+
finally:
|
| 147 |
+
self._errors = None
|
| 148 |
+
|
| 149 |
+
def create_task(self, coro, *, name=None, context=None):
|
| 150 |
+
"""Create a new task in this group and return it.
|
| 151 |
+
|
| 152 |
+
Similar to `asyncio.create_task`.
|
| 153 |
+
"""
|
| 154 |
+
if not self._entered:
|
| 155 |
+
raise RuntimeError(f"TaskGroup {self!r} has not been entered")
|
| 156 |
+
if self._exiting and not self._tasks:
|
| 157 |
+
raise RuntimeError(f"TaskGroup {self!r} is finished")
|
| 158 |
+
if self._aborting:
|
| 159 |
+
raise RuntimeError(f"TaskGroup {self!r} is shutting down")
|
| 160 |
+
if context is None:
|
| 161 |
+
task = self._loop.create_task(coro)
|
| 162 |
+
else:
|
| 163 |
+
task = self._loop.create_task(coro, context=context)
|
| 164 |
+
tasks._set_task_name(task, name)
|
| 165 |
+
task.add_done_callback(self._on_task_done)
|
| 166 |
+
self._tasks.add(task)
|
| 167 |
+
return task
|
| 168 |
+
|
| 169 |
+
# Since Python 3.8 Tasks propagate all exceptions correctly,
|
| 170 |
+
# except for KeyboardInterrupt and SystemExit which are
|
| 171 |
+
# still considered special.
|
| 172 |
+
|
| 173 |
+
def _is_base_error(self, exc: BaseException) -> bool:
|
| 174 |
+
assert isinstance(exc, BaseException)
|
| 175 |
+
return isinstance(exc, (SystemExit, KeyboardInterrupt))
|
| 176 |
+
|
| 177 |
+
def _abort(self):
|
| 178 |
+
self._aborting = True
|
| 179 |
+
|
| 180 |
+
for t in self._tasks:
|
| 181 |
+
if not t.done():
|
| 182 |
+
t.cancel()
|
| 183 |
+
|
| 184 |
+
def _on_task_done(self, task):
|
| 185 |
+
self._tasks.discard(task)
|
| 186 |
+
|
| 187 |
+
if self._on_completed_fut is not None and not self._tasks:
|
| 188 |
+
if not self._on_completed_fut.done():
|
| 189 |
+
self._on_completed_fut.set_result(True)
|
| 190 |
+
|
| 191 |
+
if task.cancelled():
|
| 192 |
+
return
|
| 193 |
+
|
| 194 |
+
exc = task.exception()
|
| 195 |
+
if exc is None:
|
| 196 |
+
return
|
| 197 |
+
|
| 198 |
+
self._errors.append(exc)
|
| 199 |
+
if self._is_base_error(exc) and self._base_error is None:
|
| 200 |
+
self._base_error = exc
|
| 201 |
+
|
| 202 |
+
if self._parent_task.done():
|
| 203 |
+
# Not sure if this case is possible, but we want to handle
|
| 204 |
+
# it anyways.
|
| 205 |
+
self._loop.call_exception_handler({
|
| 206 |
+
'message': f'Task {task!r} has errored out but its parent '
|
| 207 |
+
f'task {self._parent_task} is already completed',
|
| 208 |
+
'exception': exc,
|
| 209 |
+
'task': task,
|
| 210 |
+
})
|
| 211 |
+
return
|
| 212 |
+
|
| 213 |
+
if not self._aborting and not self._parent_cancel_requested:
|
| 214 |
+
# If parent task *is not* being cancelled, it means that we want
|
| 215 |
+
# to manually cancel it to abort whatever is being run right now
|
| 216 |
+
# in the TaskGroup. But we want to mark parent task as
|
| 217 |
+
# "not cancelled" later in __aexit__. Example situation that
|
| 218 |
+
# we need to handle:
|
| 219 |
+
#
|
| 220 |
+
# async def foo():
|
| 221 |
+
# try:
|
| 222 |
+
# async with TaskGroup() as g:
|
| 223 |
+
# g.create_task(crash_soon())
|
| 224 |
+
# await something # <- this needs to be canceled
|
| 225 |
+
# # by the TaskGroup, e.g.
|
| 226 |
+
# # foo() needs to be cancelled
|
| 227 |
+
# except Exception:
|
| 228 |
+
# # Ignore any exceptions raised in the TaskGroup
|
| 229 |
+
# pass
|
| 230 |
+
# await something_else # this line has to be called
|
| 231 |
+
# # after TaskGroup is finished.
|
| 232 |
+
self._abort()
|
| 233 |
+
self._parent_cancel_requested = True
|
| 234 |
+
self._parent_task.cancel()
|
micromamba_root/envs/pytorch_env/Lib/asyncio/tasks.py
ADDED
|
@@ -0,0 +1,990 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Support for tasks, coroutines and the scheduler."""
|
| 2 |
+
|
| 3 |
+
__all__ = (
|
| 4 |
+
'Task', 'create_task',
|
| 5 |
+
'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
|
| 6 |
+
'wait', 'wait_for', 'as_completed', 'sleep',
|
| 7 |
+
'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
|
| 8 |
+
'current_task', 'all_tasks',
|
| 9 |
+
'_register_task', '_unregister_task', '_enter_task', '_leave_task',
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
import concurrent.futures
|
| 13 |
+
import contextvars
|
| 14 |
+
import functools
|
| 15 |
+
import inspect
|
| 16 |
+
import itertools
|
| 17 |
+
import types
|
| 18 |
+
import warnings
|
| 19 |
+
import weakref
|
| 20 |
+
from types import GenericAlias
|
| 21 |
+
|
| 22 |
+
from . import base_tasks
|
| 23 |
+
from . import coroutines
|
| 24 |
+
from . import events
|
| 25 |
+
from . import exceptions
|
| 26 |
+
from . import futures
|
| 27 |
+
from .coroutines import _is_coroutine
|
| 28 |
+
|
| 29 |
+
# Helper to generate new task names
|
| 30 |
+
# This uses itertools.count() instead of a "+= 1" operation because the latter
|
| 31 |
+
# is not thread safe. See bpo-11866 for a longer explanation.
|
| 32 |
+
_task_name_counter = itertools.count(1).__next__
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def current_task(loop=None):
|
| 36 |
+
"""Return a currently executed task."""
|
| 37 |
+
if loop is None:
|
| 38 |
+
loop = events.get_running_loop()
|
| 39 |
+
return _current_tasks.get(loop)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def all_tasks(loop=None):
|
| 43 |
+
"""Return a set of all tasks for the loop."""
|
| 44 |
+
if loop is None:
|
| 45 |
+
loop = events.get_running_loop()
|
| 46 |
+
# Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
|
| 47 |
+
# thread while we do so. Therefore we cast it to list prior to filtering. The list
|
| 48 |
+
# cast itself requires iteration, so we repeat it several times ignoring
|
| 49 |
+
# RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
|
| 50 |
+
# details.
|
| 51 |
+
i = 0
|
| 52 |
+
while True:
|
| 53 |
+
try:
|
| 54 |
+
tasks = list(_all_tasks)
|
| 55 |
+
except RuntimeError:
|
| 56 |
+
i += 1
|
| 57 |
+
if i >= 1000:
|
| 58 |
+
raise
|
| 59 |
+
else:
|
| 60 |
+
break
|
| 61 |
+
return {t for t in tasks
|
| 62 |
+
if futures._get_loop(t) is loop and not t.done()}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _set_task_name(task, name):
|
| 66 |
+
if name is not None:
|
| 67 |
+
try:
|
| 68 |
+
set_name = task.set_name
|
| 69 |
+
except AttributeError:
|
| 70 |
+
warnings.warn("Task.set_name() was added in Python 3.8, "
|
| 71 |
+
"the method support will be mandatory for third-party "
|
| 72 |
+
"task implementations since 3.13.",
|
| 73 |
+
DeprecationWarning, stacklevel=3)
|
| 74 |
+
else:
|
| 75 |
+
set_name(name)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class Task(futures._PyFuture): # Inherit Python Task implementation
|
| 79 |
+
# from a Python Future implementation.
|
| 80 |
+
|
| 81 |
+
"""A coroutine wrapped in a Future."""
|
| 82 |
+
|
| 83 |
+
# An important invariant maintained while a Task not done:
|
| 84 |
+
# _fut_waiter is either None or a Future. The Future
|
| 85 |
+
# can be either done() or not done().
|
| 86 |
+
# The task can be in any of 3 states:
|
| 87 |
+
#
|
| 88 |
+
# - 1: _fut_waiter is not None and not _fut_waiter.done():
|
| 89 |
+
# __step() is *not* scheduled and the Task is waiting for _fut_waiter.
|
| 90 |
+
# - 2: (_fut_waiter is None or _fut_waiter.done()) and __step() is scheduled:
|
| 91 |
+
# the Task is waiting for __step() to be executed.
|
| 92 |
+
# - 3: _fut_waiter is None and __step() is *not* scheduled:
|
| 93 |
+
# the Task is currently executing (in __step()).
|
| 94 |
+
#
|
| 95 |
+
# * In state 1, one of the callbacks of __fut_waiter must be __wakeup().
|
| 96 |
+
# * The transition from 1 to 2 happens when _fut_waiter becomes done(),
|
| 97 |
+
# as it schedules __wakeup() to be called (which calls __step() so
|
| 98 |
+
# we way that __step() is scheduled).
|
| 99 |
+
# * It transitions from 2 to 3 when __step() is executed, and it clears
|
| 100 |
+
# _fut_waiter to None.
|
| 101 |
+
|
| 102 |
+
# If False, don't log a message if the task is destroyed while its
|
| 103 |
+
# status is still pending
|
| 104 |
+
_log_destroy_pending = True
|
| 105 |
+
|
| 106 |
+
def __init__(self, coro, *, loop=None, name=None, context=None):
|
| 107 |
+
super().__init__(loop=loop)
|
| 108 |
+
if self._source_traceback:
|
| 109 |
+
del self._source_traceback[-1]
|
| 110 |
+
if not coroutines.iscoroutine(coro):
|
| 111 |
+
# raise after Future.__init__(), attrs are required for __del__
|
| 112 |
+
# prevent logging for pending task in __del__
|
| 113 |
+
self._log_destroy_pending = False
|
| 114 |
+
raise TypeError(f"a coroutine was expected, got {coro!r}")
|
| 115 |
+
|
| 116 |
+
if name is None:
|
| 117 |
+
self._name = f'Task-{_task_name_counter()}'
|
| 118 |
+
else:
|
| 119 |
+
self._name = str(name)
|
| 120 |
+
|
| 121 |
+
self._num_cancels_requested = 0
|
| 122 |
+
self._must_cancel = False
|
| 123 |
+
self._fut_waiter = None
|
| 124 |
+
self._coro = coro
|
| 125 |
+
if context is None:
|
| 126 |
+
self._context = contextvars.copy_context()
|
| 127 |
+
else:
|
| 128 |
+
self._context = context
|
| 129 |
+
|
| 130 |
+
self._loop.call_soon(self.__step, context=self._context)
|
| 131 |
+
_register_task(self)
|
| 132 |
+
|
| 133 |
+
def __del__(self):
|
| 134 |
+
if self._state == futures._PENDING and self._log_destroy_pending:
|
| 135 |
+
context = {
|
| 136 |
+
'task': self,
|
| 137 |
+
'message': 'Task was destroyed but it is pending!',
|
| 138 |
+
}
|
| 139 |
+
if self._source_traceback:
|
| 140 |
+
context['source_traceback'] = self._source_traceback
|
| 141 |
+
self._loop.call_exception_handler(context)
|
| 142 |
+
super().__del__()
|
| 143 |
+
|
| 144 |
+
__class_getitem__ = classmethod(GenericAlias)
|
| 145 |
+
|
| 146 |
+
def __repr__(self):
|
| 147 |
+
return base_tasks._task_repr(self)
|
| 148 |
+
|
| 149 |
+
def get_coro(self):
|
| 150 |
+
return self._coro
|
| 151 |
+
|
| 152 |
+
def get_name(self):
|
| 153 |
+
return self._name
|
| 154 |
+
|
| 155 |
+
def set_name(self, value):
|
| 156 |
+
self._name = str(value)
|
| 157 |
+
|
| 158 |
+
def set_result(self, result):
|
| 159 |
+
raise RuntimeError('Task does not support set_result operation')
|
| 160 |
+
|
| 161 |
+
def set_exception(self, exception):
|
| 162 |
+
raise RuntimeError('Task does not support set_exception operation')
|
| 163 |
+
|
| 164 |
+
def get_stack(self, *, limit=None):
|
| 165 |
+
"""Return the list of stack frames for this task's coroutine.
|
| 166 |
+
|
| 167 |
+
If the coroutine is not done, this returns the stack where it is
|
| 168 |
+
suspended. If the coroutine has completed successfully or was
|
| 169 |
+
cancelled, this returns an empty list. If the coroutine was
|
| 170 |
+
terminated by an exception, this returns the list of traceback
|
| 171 |
+
frames.
|
| 172 |
+
|
| 173 |
+
The frames are always ordered from oldest to newest.
|
| 174 |
+
|
| 175 |
+
The optional limit gives the maximum number of frames to
|
| 176 |
+
return; by default all available frames are returned. Its
|
| 177 |
+
meaning differs depending on whether a stack or a traceback is
|
| 178 |
+
returned: the newest frames of a stack are returned, but the
|
| 179 |
+
oldest frames of a traceback are returned. (This matches the
|
| 180 |
+
behavior of the traceback module.)
|
| 181 |
+
|
| 182 |
+
For reasons beyond our control, only one stack frame is
|
| 183 |
+
returned for a suspended coroutine.
|
| 184 |
+
"""
|
| 185 |
+
return base_tasks._task_get_stack(self, limit)
|
| 186 |
+
|
| 187 |
+
def print_stack(self, *, limit=None, file=None):
|
| 188 |
+
"""Print the stack or traceback for this task's coroutine.
|
| 189 |
+
|
| 190 |
+
This produces output similar to that of the traceback module,
|
| 191 |
+
for the frames retrieved by get_stack(). The limit argument
|
| 192 |
+
is passed to get_stack(). The file argument is an I/O stream
|
| 193 |
+
to which the output is written; by default output is written
|
| 194 |
+
to sys.stderr.
|
| 195 |
+
"""
|
| 196 |
+
return base_tasks._task_print_stack(self, limit, file)
|
| 197 |
+
|
| 198 |
+
def cancel(self, msg=None):
|
| 199 |
+
"""Request that this task cancel itself.
|
| 200 |
+
|
| 201 |
+
This arranges for a CancelledError to be thrown into the
|
| 202 |
+
wrapped coroutine on the next cycle through the event loop.
|
| 203 |
+
The coroutine then has a chance to clean up or even deny
|
| 204 |
+
the request using try/except/finally.
|
| 205 |
+
|
| 206 |
+
Unlike Future.cancel, this does not guarantee that the
|
| 207 |
+
task will be cancelled: the exception might be caught and
|
| 208 |
+
acted upon, delaying cancellation of the task or preventing
|
| 209 |
+
cancellation completely. The task may also return a value or
|
| 210 |
+
raise a different exception.
|
| 211 |
+
|
| 212 |
+
Immediately after this method is called, Task.cancelled() will
|
| 213 |
+
not return True (unless the task was already cancelled). A
|
| 214 |
+
task will be marked as cancelled when the wrapped coroutine
|
| 215 |
+
terminates with a CancelledError exception (even if cancel()
|
| 216 |
+
was not called).
|
| 217 |
+
|
| 218 |
+
This also increases the task's count of cancellation requests.
|
| 219 |
+
"""
|
| 220 |
+
self._log_traceback = False
|
| 221 |
+
if self.done():
|
| 222 |
+
return False
|
| 223 |
+
self._num_cancels_requested += 1
|
| 224 |
+
# These two lines are controversial. See discussion starting at
|
| 225 |
+
# https://github.com/python/cpython/pull/31394#issuecomment-1053545331
|
| 226 |
+
# Also remember that this is duplicated in _asynciomodule.c.
|
| 227 |
+
# if self._num_cancels_requested > 1:
|
| 228 |
+
# return False
|
| 229 |
+
if self._fut_waiter is not None:
|
| 230 |
+
if self._fut_waiter.cancel(msg=msg):
|
| 231 |
+
# Leave self._fut_waiter; it may be a Task that
|
| 232 |
+
# catches and ignores the cancellation so we may have
|
| 233 |
+
# to cancel it again later.
|
| 234 |
+
return True
|
| 235 |
+
# It must be the case that self.__step is already scheduled.
|
| 236 |
+
self._must_cancel = True
|
| 237 |
+
self._cancel_message = msg
|
| 238 |
+
return True
|
| 239 |
+
|
| 240 |
+
def cancelling(self):
|
| 241 |
+
"""Return the count of the task's cancellation requests.
|
| 242 |
+
|
| 243 |
+
This count is incremented when .cancel() is called
|
| 244 |
+
and may be decremented using .uncancel().
|
| 245 |
+
"""
|
| 246 |
+
return self._num_cancels_requested
|
| 247 |
+
|
| 248 |
+
def uncancel(self):
|
| 249 |
+
"""Decrement the task's count of cancellation requests.
|
| 250 |
+
|
| 251 |
+
This should be called by the party that called `cancel()` on the task
|
| 252 |
+
beforehand.
|
| 253 |
+
|
| 254 |
+
Returns the remaining number of cancellation requests.
|
| 255 |
+
"""
|
| 256 |
+
if self._num_cancels_requested > 0:
|
| 257 |
+
self._num_cancels_requested -= 1
|
| 258 |
+
return self._num_cancels_requested
|
| 259 |
+
|
| 260 |
+
def __step(self, exc=None):
|
| 261 |
+
if self.done():
|
| 262 |
+
raise exceptions.InvalidStateError(
|
| 263 |
+
f'_step(): already done: {self!r}, {exc!r}')
|
| 264 |
+
if self._must_cancel:
|
| 265 |
+
if not isinstance(exc, exceptions.CancelledError):
|
| 266 |
+
exc = self._make_cancelled_error()
|
| 267 |
+
self._must_cancel = False
|
| 268 |
+
coro = self._coro
|
| 269 |
+
self._fut_waiter = None
|
| 270 |
+
|
| 271 |
+
_enter_task(self._loop, self)
|
| 272 |
+
# Call either coro.throw(exc) or coro.send(None).
|
| 273 |
+
try:
|
| 274 |
+
if exc is None:
|
| 275 |
+
# We use the `send` method directly, because coroutines
|
| 276 |
+
# don't have `__iter__` and `__next__` methods.
|
| 277 |
+
result = coro.send(None)
|
| 278 |
+
else:
|
| 279 |
+
result = coro.throw(exc)
|
| 280 |
+
except StopIteration as exc:
|
| 281 |
+
if self._must_cancel:
|
| 282 |
+
# Task is cancelled right before coro stops.
|
| 283 |
+
self._must_cancel = False
|
| 284 |
+
super().cancel(msg=self._cancel_message)
|
| 285 |
+
else:
|
| 286 |
+
super().set_result(exc.value)
|
| 287 |
+
except exceptions.CancelledError as exc:
|
| 288 |
+
# Save the original exception so we can chain it later.
|
| 289 |
+
self._cancelled_exc = exc
|
| 290 |
+
super().cancel() # I.e., Future.cancel(self).
|
| 291 |
+
except (KeyboardInterrupt, SystemExit) as exc:
|
| 292 |
+
super().set_exception(exc)
|
| 293 |
+
raise
|
| 294 |
+
except BaseException as exc:
|
| 295 |
+
super().set_exception(exc)
|
| 296 |
+
else:
|
| 297 |
+
blocking = getattr(result, '_asyncio_future_blocking', None)
|
| 298 |
+
if blocking is not None:
|
| 299 |
+
# Yielded Future must come from Future.__iter__().
|
| 300 |
+
if futures._get_loop(result) is not self._loop:
|
| 301 |
+
new_exc = RuntimeError(
|
| 302 |
+
f'Task {self!r} got Future '
|
| 303 |
+
f'{result!r} attached to a different loop')
|
| 304 |
+
self._loop.call_soon(
|
| 305 |
+
self.__step, new_exc, context=self._context)
|
| 306 |
+
elif blocking:
|
| 307 |
+
if result is self:
|
| 308 |
+
new_exc = RuntimeError(
|
| 309 |
+
f'Task cannot await on itself: {self!r}')
|
| 310 |
+
self._loop.call_soon(
|
| 311 |
+
self.__step, new_exc, context=self._context)
|
| 312 |
+
else:
|
| 313 |
+
result._asyncio_future_blocking = False
|
| 314 |
+
result.add_done_callback(
|
| 315 |
+
self.__wakeup, context=self._context)
|
| 316 |
+
self._fut_waiter = result
|
| 317 |
+
if self._must_cancel:
|
| 318 |
+
if self._fut_waiter.cancel(
|
| 319 |
+
msg=self._cancel_message):
|
| 320 |
+
self._must_cancel = False
|
| 321 |
+
else:
|
| 322 |
+
new_exc = RuntimeError(
|
| 323 |
+
f'yield was used instead of yield from '
|
| 324 |
+
f'in task {self!r} with {result!r}')
|
| 325 |
+
self._loop.call_soon(
|
| 326 |
+
self.__step, new_exc, context=self._context)
|
| 327 |
+
|
| 328 |
+
elif result is None:
|
| 329 |
+
# Bare yield relinquishes control for one event loop iteration.
|
| 330 |
+
self._loop.call_soon(self.__step, context=self._context)
|
| 331 |
+
elif inspect.isgenerator(result):
|
| 332 |
+
# Yielding a generator is just wrong.
|
| 333 |
+
new_exc = RuntimeError(
|
| 334 |
+
f'yield was used instead of yield from for '
|
| 335 |
+
f'generator in task {self!r} with {result!r}')
|
| 336 |
+
self._loop.call_soon(
|
| 337 |
+
self.__step, new_exc, context=self._context)
|
| 338 |
+
else:
|
| 339 |
+
# Yielding something else is an error.
|
| 340 |
+
new_exc = RuntimeError(f'Task got bad yield: {result!r}')
|
| 341 |
+
self._loop.call_soon(
|
| 342 |
+
self.__step, new_exc, context=self._context)
|
| 343 |
+
finally:
|
| 344 |
+
_leave_task(self._loop, self)
|
| 345 |
+
self = None # Needed to break cycles when an exception occurs.
|
| 346 |
+
|
| 347 |
+
def __wakeup(self, future):
|
| 348 |
+
try:
|
| 349 |
+
future.result()
|
| 350 |
+
except BaseException as exc:
|
| 351 |
+
# This may also be a cancellation.
|
| 352 |
+
self.__step(exc)
|
| 353 |
+
else:
|
| 354 |
+
# Don't pass the value of `future.result()` explicitly,
|
| 355 |
+
# as `Future.__iter__` and `Future.__await__` don't need it.
|
| 356 |
+
# If we call `_step(value, None)` instead of `_step()`,
|
| 357 |
+
# Python eval loop would use `.send(value)` method call,
|
| 358 |
+
# instead of `__next__()`, which is slower for futures
|
| 359 |
+
# that return non-generator iterators from their `__iter__`.
|
| 360 |
+
self.__step()
|
| 361 |
+
self = None # Needed to break cycles when an exception occurs.
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
_PyTask = Task
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
try:
|
| 368 |
+
import _asyncio
|
| 369 |
+
except ImportError:
|
| 370 |
+
pass
|
| 371 |
+
else:
|
| 372 |
+
# _CTask is needed for tests.
|
| 373 |
+
Task = _CTask = _asyncio.Task
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def create_task(coro, *, name=None, context=None):
|
| 377 |
+
"""Schedule the execution of a coroutine object in a spawn task.
|
| 378 |
+
|
| 379 |
+
Return a Task object.
|
| 380 |
+
"""
|
| 381 |
+
loop = events.get_running_loop()
|
| 382 |
+
if context is None:
|
| 383 |
+
# Use legacy API if context is not needed
|
| 384 |
+
task = loop.create_task(coro)
|
| 385 |
+
else:
|
| 386 |
+
task = loop.create_task(coro, context=context)
|
| 387 |
+
|
| 388 |
+
_set_task_name(task, name)
|
| 389 |
+
return task
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
# wait() and as_completed() similar to those in PEP 3148.
|
| 393 |
+
|
| 394 |
+
FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
|
| 395 |
+
FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
|
| 396 |
+
ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
async def wait(fs, *, timeout=None, return_when=ALL_COMPLETED):
|
| 400 |
+
"""Wait for the Futures or Tasks given by fs to complete.
|
| 401 |
+
|
| 402 |
+
The fs iterable must not be empty.
|
| 403 |
+
|
| 404 |
+
Coroutines will be wrapped in Tasks.
|
| 405 |
+
|
| 406 |
+
Returns two sets of Future: (done, pending).
|
| 407 |
+
|
| 408 |
+
Usage:
|
| 409 |
+
|
| 410 |
+
done, pending = await asyncio.wait(fs)
|
| 411 |
+
|
| 412 |
+
Note: This does not raise TimeoutError! Futures that aren't done
|
| 413 |
+
when the timeout occurs are returned in the second set.
|
| 414 |
+
"""
|
| 415 |
+
if futures.isfuture(fs) or coroutines.iscoroutine(fs):
|
| 416 |
+
raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
|
| 417 |
+
if not fs:
|
| 418 |
+
raise ValueError('Set of Tasks/Futures is empty.')
|
| 419 |
+
if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
|
| 420 |
+
raise ValueError(f'Invalid return_when value: {return_when}')
|
| 421 |
+
|
| 422 |
+
fs = set(fs)
|
| 423 |
+
|
| 424 |
+
if any(coroutines.iscoroutine(f) for f in fs):
|
| 425 |
+
raise TypeError("Passing coroutines is forbidden, use tasks explicitly.")
|
| 426 |
+
|
| 427 |
+
loop = events.get_running_loop()
|
| 428 |
+
return await _wait(fs, timeout, return_when, loop)
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
def _release_waiter(waiter, *args):
|
| 432 |
+
if not waiter.done():
|
| 433 |
+
waiter.set_result(None)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
async def wait_for(fut, timeout):
|
| 437 |
+
"""Wait for the single Future or coroutine to complete, with timeout.
|
| 438 |
+
|
| 439 |
+
Coroutine will be wrapped in Task.
|
| 440 |
+
|
| 441 |
+
Returns result of the Future or coroutine. When a timeout occurs,
|
| 442 |
+
it cancels the task and raises TimeoutError. To avoid the task
|
| 443 |
+
cancellation, wrap it in shield().
|
| 444 |
+
|
| 445 |
+
If the wait is cancelled, the task is also cancelled.
|
| 446 |
+
|
| 447 |
+
This function is a coroutine.
|
| 448 |
+
"""
|
| 449 |
+
loop = events.get_running_loop()
|
| 450 |
+
|
| 451 |
+
if timeout is None:
|
| 452 |
+
return await fut
|
| 453 |
+
|
| 454 |
+
if timeout <= 0:
|
| 455 |
+
fut = ensure_future(fut, loop=loop)
|
| 456 |
+
|
| 457 |
+
if fut.done():
|
| 458 |
+
return fut.result()
|
| 459 |
+
|
| 460 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 461 |
+
try:
|
| 462 |
+
return fut.result()
|
| 463 |
+
except exceptions.CancelledError as exc:
|
| 464 |
+
raise exceptions.TimeoutError() from exc
|
| 465 |
+
|
| 466 |
+
waiter = loop.create_future()
|
| 467 |
+
timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
|
| 468 |
+
cb = functools.partial(_release_waiter, waiter)
|
| 469 |
+
|
| 470 |
+
fut = ensure_future(fut, loop=loop)
|
| 471 |
+
fut.add_done_callback(cb)
|
| 472 |
+
|
| 473 |
+
try:
|
| 474 |
+
# wait until the future completes or the timeout
|
| 475 |
+
try:
|
| 476 |
+
await waiter
|
| 477 |
+
except exceptions.CancelledError:
|
| 478 |
+
if fut.done():
|
| 479 |
+
return fut.result()
|
| 480 |
+
else:
|
| 481 |
+
fut.remove_done_callback(cb)
|
| 482 |
+
# We must ensure that the task is not running
|
| 483 |
+
# after wait_for() returns.
|
| 484 |
+
# See https://bugs.python.org/issue32751
|
| 485 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 486 |
+
raise
|
| 487 |
+
|
| 488 |
+
if fut.done():
|
| 489 |
+
return fut.result()
|
| 490 |
+
else:
|
| 491 |
+
fut.remove_done_callback(cb)
|
| 492 |
+
# We must ensure that the task is not running
|
| 493 |
+
# after wait_for() returns.
|
| 494 |
+
# See https://bugs.python.org/issue32751
|
| 495 |
+
await _cancel_and_wait(fut, loop=loop)
|
| 496 |
+
# In case task cancellation failed with some
|
| 497 |
+
# exception, we should re-raise it
|
| 498 |
+
# See https://bugs.python.org/issue40607
|
| 499 |
+
try:
|
| 500 |
+
return fut.result()
|
| 501 |
+
except exceptions.CancelledError as exc:
|
| 502 |
+
raise exceptions.TimeoutError() from exc
|
| 503 |
+
finally:
|
| 504 |
+
timeout_handle.cancel()
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
async def _wait(fs, timeout, return_when, loop):
|
| 508 |
+
"""Internal helper for wait().
|
| 509 |
+
|
| 510 |
+
The fs argument must be a collection of Futures.
|
| 511 |
+
"""
|
| 512 |
+
assert fs, 'Set of Futures is empty.'
|
| 513 |
+
waiter = loop.create_future()
|
| 514 |
+
timeout_handle = None
|
| 515 |
+
if timeout is not None:
|
| 516 |
+
timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
|
| 517 |
+
counter = len(fs)
|
| 518 |
+
|
| 519 |
+
def _on_completion(f):
|
| 520 |
+
nonlocal counter
|
| 521 |
+
counter -= 1
|
| 522 |
+
if (counter <= 0 or
|
| 523 |
+
return_when == FIRST_COMPLETED or
|
| 524 |
+
return_when == FIRST_EXCEPTION and (not f.cancelled() and
|
| 525 |
+
f.exception() is not None)):
|
| 526 |
+
if timeout_handle is not None:
|
| 527 |
+
timeout_handle.cancel()
|
| 528 |
+
if not waiter.done():
|
| 529 |
+
waiter.set_result(None)
|
| 530 |
+
|
| 531 |
+
for f in fs:
|
| 532 |
+
f.add_done_callback(_on_completion)
|
| 533 |
+
|
| 534 |
+
try:
|
| 535 |
+
await waiter
|
| 536 |
+
finally:
|
| 537 |
+
if timeout_handle is not None:
|
| 538 |
+
timeout_handle.cancel()
|
| 539 |
+
for f in fs:
|
| 540 |
+
f.remove_done_callback(_on_completion)
|
| 541 |
+
|
| 542 |
+
done, pending = set(), set()
|
| 543 |
+
for f in fs:
|
| 544 |
+
if f.done():
|
| 545 |
+
done.add(f)
|
| 546 |
+
else:
|
| 547 |
+
pending.add(f)
|
| 548 |
+
return done, pending
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
async def _cancel_and_wait(fut, loop):
|
| 552 |
+
"""Cancel the *fut* future or task and wait until it completes."""
|
| 553 |
+
|
| 554 |
+
waiter = loop.create_future()
|
| 555 |
+
cb = functools.partial(_release_waiter, waiter)
|
| 556 |
+
fut.add_done_callback(cb)
|
| 557 |
+
|
| 558 |
+
try:
|
| 559 |
+
fut.cancel()
|
| 560 |
+
# We cannot wait on *fut* directly to make
|
| 561 |
+
# sure _cancel_and_wait itself is reliably cancellable.
|
| 562 |
+
await waiter
|
| 563 |
+
finally:
|
| 564 |
+
fut.remove_done_callback(cb)
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
# This is *not* a @coroutine! It is just an iterator (yielding Futures).
|
| 568 |
+
def as_completed(fs, *, timeout=None):
|
| 569 |
+
"""Return an iterator whose values are coroutines.
|
| 570 |
+
|
| 571 |
+
When waiting for the yielded coroutines you'll get the results (or
|
| 572 |
+
exceptions!) of the original Futures (or coroutines), in the order
|
| 573 |
+
in which and as soon as they complete.
|
| 574 |
+
|
| 575 |
+
This differs from PEP 3148; the proper way to use this is:
|
| 576 |
+
|
| 577 |
+
for f in as_completed(fs):
|
| 578 |
+
result = await f # The 'await' may raise.
|
| 579 |
+
# Use result.
|
| 580 |
+
|
| 581 |
+
If a timeout is specified, the 'await' will raise
|
| 582 |
+
TimeoutError when the timeout occurs before all Futures are done.
|
| 583 |
+
|
| 584 |
+
Note: The futures 'f' are not necessarily members of fs.
|
| 585 |
+
"""
|
| 586 |
+
if futures.isfuture(fs) or coroutines.iscoroutine(fs):
|
| 587 |
+
raise TypeError(f"expect an iterable of futures, not {type(fs).__name__}")
|
| 588 |
+
|
| 589 |
+
from .queues import Queue # Import here to avoid circular import problem.
|
| 590 |
+
done = Queue()
|
| 591 |
+
|
| 592 |
+
loop = events._get_event_loop()
|
| 593 |
+
todo = {ensure_future(f, loop=loop) for f in set(fs)}
|
| 594 |
+
timeout_handle = None
|
| 595 |
+
|
| 596 |
+
def _on_timeout():
|
| 597 |
+
for f in todo:
|
| 598 |
+
f.remove_done_callback(_on_completion)
|
| 599 |
+
done.put_nowait(None) # Queue a dummy value for _wait_for_one().
|
| 600 |
+
todo.clear() # Can't do todo.remove(f) in the loop.
|
| 601 |
+
|
| 602 |
+
def _on_completion(f):
|
| 603 |
+
if not todo:
|
| 604 |
+
return # _on_timeout() was here first.
|
| 605 |
+
todo.remove(f)
|
| 606 |
+
done.put_nowait(f)
|
| 607 |
+
if not todo and timeout_handle is not None:
|
| 608 |
+
timeout_handle.cancel()
|
| 609 |
+
|
| 610 |
+
async def _wait_for_one():
|
| 611 |
+
f = await done.get()
|
| 612 |
+
if f is None:
|
| 613 |
+
# Dummy value from _on_timeout().
|
| 614 |
+
raise exceptions.TimeoutError
|
| 615 |
+
return f.result() # May raise f.exception().
|
| 616 |
+
|
| 617 |
+
for f in todo:
|
| 618 |
+
f.add_done_callback(_on_completion)
|
| 619 |
+
if todo and timeout is not None:
|
| 620 |
+
timeout_handle = loop.call_later(timeout, _on_timeout)
|
| 621 |
+
for _ in range(len(todo)):
|
| 622 |
+
yield _wait_for_one()
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
@types.coroutine
|
| 626 |
+
def __sleep0():
|
| 627 |
+
"""Skip one event loop run cycle.
|
| 628 |
+
|
| 629 |
+
This is a private helper for 'asyncio.sleep()', used
|
| 630 |
+
when the 'delay' is set to 0. It uses a bare 'yield'
|
| 631 |
+
expression (which Task.__step knows how to handle)
|
| 632 |
+
instead of creating a Future object.
|
| 633 |
+
"""
|
| 634 |
+
yield
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
async def sleep(delay, result=None):
|
| 638 |
+
"""Coroutine that completes after a given time (in seconds)."""
|
| 639 |
+
if delay <= 0:
|
| 640 |
+
await __sleep0()
|
| 641 |
+
return result
|
| 642 |
+
|
| 643 |
+
loop = events.get_running_loop()
|
| 644 |
+
future = loop.create_future()
|
| 645 |
+
h = loop.call_later(delay,
|
| 646 |
+
futures._set_result_unless_cancelled,
|
| 647 |
+
future, result)
|
| 648 |
+
try:
|
| 649 |
+
return await future
|
| 650 |
+
finally:
|
| 651 |
+
h.cancel()
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def ensure_future(coro_or_future, *, loop=None):
|
| 655 |
+
"""Wrap a coroutine or an awaitable in a future.
|
| 656 |
+
|
| 657 |
+
If the argument is a Future, it is returned directly.
|
| 658 |
+
"""
|
| 659 |
+
return _ensure_future(coro_or_future, loop=loop)
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
def _ensure_future(coro_or_future, *, loop=None):
|
| 663 |
+
if futures.isfuture(coro_or_future):
|
| 664 |
+
if loop is not None and loop is not futures._get_loop(coro_or_future):
|
| 665 |
+
raise ValueError('The future belongs to a different loop than '
|
| 666 |
+
'the one specified as the loop argument')
|
| 667 |
+
return coro_or_future
|
| 668 |
+
called_wrap_awaitable = False
|
| 669 |
+
if not coroutines.iscoroutine(coro_or_future):
|
| 670 |
+
if inspect.isawaitable(coro_or_future):
|
| 671 |
+
coro_or_future = _wrap_awaitable(coro_or_future)
|
| 672 |
+
called_wrap_awaitable = True
|
| 673 |
+
else:
|
| 674 |
+
raise TypeError('An asyncio.Future, a coroutine or an awaitable '
|
| 675 |
+
'is required')
|
| 676 |
+
|
| 677 |
+
if loop is None:
|
| 678 |
+
loop = events._get_event_loop(stacklevel=4)
|
| 679 |
+
try:
|
| 680 |
+
return loop.create_task(coro_or_future)
|
| 681 |
+
except RuntimeError:
|
| 682 |
+
if not called_wrap_awaitable:
|
| 683 |
+
coro_or_future.close()
|
| 684 |
+
raise
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
@types.coroutine
|
| 688 |
+
def _wrap_awaitable(awaitable):
|
| 689 |
+
"""Helper for asyncio.ensure_future().
|
| 690 |
+
|
| 691 |
+
Wraps awaitable (an object with __await__) into a coroutine
|
| 692 |
+
that will later be wrapped in a Task by ensure_future().
|
| 693 |
+
"""
|
| 694 |
+
return (yield from awaitable.__await__())
|
| 695 |
+
|
| 696 |
+
_wrap_awaitable._is_coroutine = _is_coroutine
|
| 697 |
+
|
| 698 |
+
|
| 699 |
+
class _GatheringFuture(futures.Future):
|
| 700 |
+
"""Helper for gather().
|
| 701 |
+
|
| 702 |
+
This overrides cancel() to cancel all the children and act more
|
| 703 |
+
like Task.cancel(), which doesn't immediately mark itself as
|
| 704 |
+
cancelled.
|
| 705 |
+
"""
|
| 706 |
+
|
| 707 |
+
def __init__(self, children, *, loop):
|
| 708 |
+
assert loop is not None
|
| 709 |
+
super().__init__(loop=loop)
|
| 710 |
+
self._children = children
|
| 711 |
+
self._cancel_requested = False
|
| 712 |
+
|
| 713 |
+
def cancel(self, msg=None):
|
| 714 |
+
if self.done():
|
| 715 |
+
return False
|
| 716 |
+
ret = False
|
| 717 |
+
for child in self._children:
|
| 718 |
+
if child.cancel(msg=msg):
|
| 719 |
+
ret = True
|
| 720 |
+
if ret:
|
| 721 |
+
# If any child tasks were actually cancelled, we should
|
| 722 |
+
# propagate the cancellation request regardless of
|
| 723 |
+
# *return_exceptions* argument. See issue 32684.
|
| 724 |
+
self._cancel_requested = True
|
| 725 |
+
return ret
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def gather(*coros_or_futures, return_exceptions=False):
|
| 729 |
+
"""Return a future aggregating results from the given coroutines/futures.
|
| 730 |
+
|
| 731 |
+
Coroutines will be wrapped in a future and scheduled in the event
|
| 732 |
+
loop. They will not necessarily be scheduled in the same order as
|
| 733 |
+
passed in.
|
| 734 |
+
|
| 735 |
+
All futures must share the same event loop. If all the tasks are
|
| 736 |
+
done successfully, the returned future's result is the list of
|
| 737 |
+
results (in the order of the original sequence, not necessarily
|
| 738 |
+
the order of results arrival). If *return_exceptions* is True,
|
| 739 |
+
exceptions in the tasks are treated the same as successful
|
| 740 |
+
results, and gathered in the result list; otherwise, the first
|
| 741 |
+
raised exception will be immediately propagated to the returned
|
| 742 |
+
future.
|
| 743 |
+
|
| 744 |
+
Cancellation: if the outer Future is cancelled, all children (that
|
| 745 |
+
have not completed yet) are also cancelled. If any child is
|
| 746 |
+
cancelled, this is treated as if it raised CancelledError --
|
| 747 |
+
the outer Future is *not* cancelled in this case. (This is to
|
| 748 |
+
prevent the cancellation of one child to cause other children to
|
| 749 |
+
be cancelled.)
|
| 750 |
+
|
| 751 |
+
If *return_exceptions* is False, cancelling gather() after it
|
| 752 |
+
has been marked done won't cancel any submitted awaitables.
|
| 753 |
+
For instance, gather can be marked done after propagating an
|
| 754 |
+
exception to the caller, therefore, calling ``gather.cancel()``
|
| 755 |
+
after catching an exception (raised by one of the awaitables) from
|
| 756 |
+
gather won't cancel any other awaitables.
|
| 757 |
+
"""
|
| 758 |
+
if not coros_or_futures:
|
| 759 |
+
loop = events._get_event_loop()
|
| 760 |
+
outer = loop.create_future()
|
| 761 |
+
outer.set_result([])
|
| 762 |
+
return outer
|
| 763 |
+
|
| 764 |
+
def _done_callback(fut):
|
| 765 |
+
nonlocal nfinished
|
| 766 |
+
nfinished += 1
|
| 767 |
+
|
| 768 |
+
if outer is None or outer.done():
|
| 769 |
+
if not fut.cancelled():
|
| 770 |
+
# Mark exception retrieved.
|
| 771 |
+
fut.exception()
|
| 772 |
+
return
|
| 773 |
+
|
| 774 |
+
if not return_exceptions:
|
| 775 |
+
if fut.cancelled():
|
| 776 |
+
# Check if 'fut' is cancelled first, as
|
| 777 |
+
# 'fut.exception()' will *raise* a CancelledError
|
| 778 |
+
# instead of returning it.
|
| 779 |
+
exc = fut._make_cancelled_error()
|
| 780 |
+
outer.set_exception(exc)
|
| 781 |
+
return
|
| 782 |
+
else:
|
| 783 |
+
exc = fut.exception()
|
| 784 |
+
if exc is not None:
|
| 785 |
+
outer.set_exception(exc)
|
| 786 |
+
return
|
| 787 |
+
|
| 788 |
+
if nfinished == nfuts:
|
| 789 |
+
# All futures are done; create a list of results
|
| 790 |
+
# and set it to the 'outer' future.
|
| 791 |
+
results = []
|
| 792 |
+
|
| 793 |
+
for fut in children:
|
| 794 |
+
if fut.cancelled():
|
| 795 |
+
# Check if 'fut' is cancelled first, as 'fut.exception()'
|
| 796 |
+
# will *raise* a CancelledError instead of returning it.
|
| 797 |
+
# Also, since we're adding the exception return value
|
| 798 |
+
# to 'results' instead of raising it, don't bother
|
| 799 |
+
# setting __context__. This also lets us preserve
|
| 800 |
+
# calling '_make_cancelled_error()' at most once.
|
| 801 |
+
res = exceptions.CancelledError(
|
| 802 |
+
'' if fut._cancel_message is None else
|
| 803 |
+
fut._cancel_message)
|
| 804 |
+
else:
|
| 805 |
+
res = fut.exception()
|
| 806 |
+
if res is None:
|
| 807 |
+
res = fut.result()
|
| 808 |
+
results.append(res)
|
| 809 |
+
|
| 810 |
+
if outer._cancel_requested:
|
| 811 |
+
# If gather is being cancelled we must propagate the
|
| 812 |
+
# cancellation regardless of *return_exceptions* argument.
|
| 813 |
+
# See issue 32684.
|
| 814 |
+
exc = fut._make_cancelled_error()
|
| 815 |
+
outer.set_exception(exc)
|
| 816 |
+
else:
|
| 817 |
+
outer.set_result(results)
|
| 818 |
+
|
| 819 |
+
arg_to_fut = {}
|
| 820 |
+
children = []
|
| 821 |
+
nfuts = 0
|
| 822 |
+
nfinished = 0
|
| 823 |
+
loop = None
|
| 824 |
+
outer = None # bpo-46672
|
| 825 |
+
for arg in coros_or_futures:
|
| 826 |
+
if arg not in arg_to_fut:
|
| 827 |
+
fut = _ensure_future(arg, loop=loop)
|
| 828 |
+
if loop is None:
|
| 829 |
+
loop = futures._get_loop(fut)
|
| 830 |
+
if fut is not arg:
|
| 831 |
+
# 'arg' was not a Future, therefore, 'fut' is a new
|
| 832 |
+
# Future created specifically for 'arg'. Since the caller
|
| 833 |
+
# can't control it, disable the "destroy pending task"
|
| 834 |
+
# warning.
|
| 835 |
+
fut._log_destroy_pending = False
|
| 836 |
+
|
| 837 |
+
nfuts += 1
|
| 838 |
+
arg_to_fut[arg] = fut
|
| 839 |
+
fut.add_done_callback(_done_callback)
|
| 840 |
+
|
| 841 |
+
else:
|
| 842 |
+
# There's a duplicate Future object in coros_or_futures.
|
| 843 |
+
fut = arg_to_fut[arg]
|
| 844 |
+
|
| 845 |
+
children.append(fut)
|
| 846 |
+
|
| 847 |
+
outer = _GatheringFuture(children, loop=loop)
|
| 848 |
+
return outer
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
def shield(arg):
|
| 852 |
+
"""Wait for a future, shielding it from cancellation.
|
| 853 |
+
|
| 854 |
+
The statement
|
| 855 |
+
|
| 856 |
+
task = asyncio.create_task(something())
|
| 857 |
+
res = await shield(task)
|
| 858 |
+
|
| 859 |
+
is exactly equivalent to the statement
|
| 860 |
+
|
| 861 |
+
res = await something()
|
| 862 |
+
|
| 863 |
+
*except* that if the coroutine containing it is cancelled, the
|
| 864 |
+
task running in something() is not cancelled. From the POV of
|
| 865 |
+
something(), the cancellation did not happen. But its caller is
|
| 866 |
+
still cancelled, so the yield-from expression still raises
|
| 867 |
+
CancelledError. Note: If something() is cancelled by other means
|
| 868 |
+
this will still cancel shield().
|
| 869 |
+
|
| 870 |
+
If you want to completely ignore cancellation (not recommended)
|
| 871 |
+
you can combine shield() with a try/except clause, as follows:
|
| 872 |
+
|
| 873 |
+
task = asyncio.create_task(something())
|
| 874 |
+
try:
|
| 875 |
+
res = await shield(task)
|
| 876 |
+
except CancelledError:
|
| 877 |
+
res = None
|
| 878 |
+
|
| 879 |
+
Save a reference to tasks passed to this function, to avoid
|
| 880 |
+
a task disappearing mid-execution. The event loop only keeps
|
| 881 |
+
weak references to tasks. A task that isn't referenced elsewhere
|
| 882 |
+
may get garbage collected at any time, even before it's done.
|
| 883 |
+
"""
|
| 884 |
+
inner = _ensure_future(arg)
|
| 885 |
+
if inner.done():
|
| 886 |
+
# Shortcut.
|
| 887 |
+
return inner
|
| 888 |
+
loop = futures._get_loop(inner)
|
| 889 |
+
outer = loop.create_future()
|
| 890 |
+
|
| 891 |
+
def _inner_done_callback(inner):
|
| 892 |
+
if outer.cancelled():
|
| 893 |
+
if not inner.cancelled():
|
| 894 |
+
# Mark inner's result as retrieved.
|
| 895 |
+
inner.exception()
|
| 896 |
+
return
|
| 897 |
+
|
| 898 |
+
if inner.cancelled():
|
| 899 |
+
outer.cancel()
|
| 900 |
+
else:
|
| 901 |
+
exc = inner.exception()
|
| 902 |
+
if exc is not None:
|
| 903 |
+
outer.set_exception(exc)
|
| 904 |
+
else:
|
| 905 |
+
outer.set_result(inner.result())
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
def _outer_done_callback(outer):
|
| 909 |
+
if not inner.done():
|
| 910 |
+
inner.remove_done_callback(_inner_done_callback)
|
| 911 |
+
|
| 912 |
+
inner.add_done_callback(_inner_done_callback)
|
| 913 |
+
outer.add_done_callback(_outer_done_callback)
|
| 914 |
+
return outer
|
| 915 |
+
|
| 916 |
+
|
| 917 |
+
def run_coroutine_threadsafe(coro, loop):
|
| 918 |
+
"""Submit a coroutine object to a given event loop.
|
| 919 |
+
|
| 920 |
+
Return a concurrent.futures.Future to access the result.
|
| 921 |
+
"""
|
| 922 |
+
if not coroutines.iscoroutine(coro):
|
| 923 |
+
raise TypeError('A coroutine object is required')
|
| 924 |
+
future = concurrent.futures.Future()
|
| 925 |
+
|
| 926 |
+
def callback():
|
| 927 |
+
try:
|
| 928 |
+
futures._chain_future(ensure_future(coro, loop=loop), future)
|
| 929 |
+
except (SystemExit, KeyboardInterrupt):
|
| 930 |
+
raise
|
| 931 |
+
except BaseException as exc:
|
| 932 |
+
if future.set_running_or_notify_cancel():
|
| 933 |
+
future.set_exception(exc)
|
| 934 |
+
raise
|
| 935 |
+
|
| 936 |
+
loop.call_soon_threadsafe(callback)
|
| 937 |
+
return future
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
# WeakSet containing all alive tasks.
|
| 941 |
+
_all_tasks = weakref.WeakSet()
|
| 942 |
+
|
| 943 |
+
# Dictionary containing tasks that are currently active in
|
| 944 |
+
# all running event loops. {EventLoop: Task}
|
| 945 |
+
_current_tasks = {}
|
| 946 |
+
|
| 947 |
+
|
| 948 |
+
def _register_task(task):
|
| 949 |
+
"""Register a new task in asyncio as executed by loop."""
|
| 950 |
+
_all_tasks.add(task)
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
def _enter_task(loop, task):
|
| 954 |
+
current_task = _current_tasks.get(loop)
|
| 955 |
+
if current_task is not None:
|
| 956 |
+
raise RuntimeError(f"Cannot enter into task {task!r} while another "
|
| 957 |
+
f"task {current_task!r} is being executed.")
|
| 958 |
+
_current_tasks[loop] = task
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
def _leave_task(loop, task):
|
| 962 |
+
current_task = _current_tasks.get(loop)
|
| 963 |
+
if current_task is not task:
|
| 964 |
+
raise RuntimeError(f"Leaving task {task!r} does not match "
|
| 965 |
+
f"the current task {current_task!r}.")
|
| 966 |
+
del _current_tasks[loop]
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
def _unregister_task(task):
|
| 970 |
+
"""Unregister a task."""
|
| 971 |
+
_all_tasks.discard(task)
|
| 972 |
+
|
| 973 |
+
|
| 974 |
+
_py_register_task = _register_task
|
| 975 |
+
_py_unregister_task = _unregister_task
|
| 976 |
+
_py_enter_task = _enter_task
|
| 977 |
+
_py_leave_task = _leave_task
|
| 978 |
+
|
| 979 |
+
|
| 980 |
+
try:
|
| 981 |
+
from _asyncio import (_register_task, _unregister_task,
|
| 982 |
+
_enter_task, _leave_task,
|
| 983 |
+
_all_tasks, _current_tasks)
|
| 984 |
+
except ImportError:
|
| 985 |
+
pass
|
| 986 |
+
else:
|
| 987 |
+
_c_register_task = _register_task
|
| 988 |
+
_c_unregister_task = _unregister_task
|
| 989 |
+
_c_enter_task = _enter_task
|
| 990 |
+
_c_leave_task = _leave_task
|
micromamba_root/envs/pytorch_env/Lib/asyncio/threads.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""High-level support for working with threads in asyncio"""
|
| 2 |
+
|
| 3 |
+
import functools
|
| 4 |
+
import contextvars
|
| 5 |
+
|
| 6 |
+
from . import events
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
__all__ = "to_thread",
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
async def to_thread(func, /, *args, **kwargs):
|
| 13 |
+
"""Asynchronously run function *func* in a separate thread.
|
| 14 |
+
|
| 15 |
+
Any *args and **kwargs supplied for this function are directly passed
|
| 16 |
+
to *func*. Also, the current :class:`contextvars.Context` is propagated,
|
| 17 |
+
allowing context variables from the main thread to be accessed in the
|
| 18 |
+
separate thread.
|
| 19 |
+
|
| 20 |
+
Return a coroutine that can be awaited to get the eventual result of *func*.
|
| 21 |
+
"""
|
| 22 |
+
loop = events.get_running_loop()
|
| 23 |
+
ctx = contextvars.copy_context()
|
| 24 |
+
func_call = functools.partial(ctx.run, func, *args, **kwargs)
|
| 25 |
+
return await loop.run_in_executor(None, func_call)
|
micromamba_root/envs/pytorch_env/Lib/asyncio/timeouts.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import enum
|
| 2 |
+
|
| 3 |
+
from types import TracebackType
|
| 4 |
+
from typing import final, Optional, Type
|
| 5 |
+
|
| 6 |
+
from . import events
|
| 7 |
+
from . import exceptions
|
| 8 |
+
from . import tasks
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
__all__ = (
|
| 12 |
+
"Timeout",
|
| 13 |
+
"timeout",
|
| 14 |
+
"timeout_at",
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class _State(enum.Enum):
|
| 19 |
+
CREATED = "created"
|
| 20 |
+
ENTERED = "active"
|
| 21 |
+
EXPIRING = "expiring"
|
| 22 |
+
EXPIRED = "expired"
|
| 23 |
+
EXITED = "finished"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@final
|
| 27 |
+
class Timeout:
|
| 28 |
+
"""Asynchronous context manager for cancelling overdue coroutines.
|
| 29 |
+
|
| 30 |
+
Use `timeout()` or `timeout_at()` rather than instantiating this class directly.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, when: Optional[float]) -> None:
|
| 34 |
+
"""Schedule a timeout that will trigger at a given loop time.
|
| 35 |
+
|
| 36 |
+
- If `when` is `None`, the timeout will never trigger.
|
| 37 |
+
- If `when < loop.time()`, the timeout will trigger on the next
|
| 38 |
+
iteration of the event loop.
|
| 39 |
+
"""
|
| 40 |
+
self._state = _State.CREATED
|
| 41 |
+
|
| 42 |
+
self._timeout_handler: Optional[events.TimerHandle] = None
|
| 43 |
+
self._task: Optional[tasks.Task] = None
|
| 44 |
+
self._when = when
|
| 45 |
+
|
| 46 |
+
def when(self) -> Optional[float]:
|
| 47 |
+
"""Return the current deadline."""
|
| 48 |
+
return self._when
|
| 49 |
+
|
| 50 |
+
def reschedule(self, when: Optional[float]) -> None:
|
| 51 |
+
"""Reschedule the timeout."""
|
| 52 |
+
if self._state is not _State.ENTERED:
|
| 53 |
+
if self._state is _State.CREATED:
|
| 54 |
+
raise RuntimeError("Timeout has not been entered")
|
| 55 |
+
raise RuntimeError(
|
| 56 |
+
f"Cannot change state of {self._state.value} Timeout",
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
self._when = when
|
| 60 |
+
|
| 61 |
+
if self._timeout_handler is not None:
|
| 62 |
+
self._timeout_handler.cancel()
|
| 63 |
+
|
| 64 |
+
if when is None:
|
| 65 |
+
self._timeout_handler = None
|
| 66 |
+
else:
|
| 67 |
+
loop = events.get_running_loop()
|
| 68 |
+
if when <= loop.time():
|
| 69 |
+
self._timeout_handler = loop.call_soon(self._on_timeout)
|
| 70 |
+
else:
|
| 71 |
+
self._timeout_handler = loop.call_at(when, self._on_timeout)
|
| 72 |
+
|
| 73 |
+
def expired(self) -> bool:
|
| 74 |
+
"""Is timeout expired during execution?"""
|
| 75 |
+
return self._state in (_State.EXPIRING, _State.EXPIRED)
|
| 76 |
+
|
| 77 |
+
def __repr__(self) -> str:
|
| 78 |
+
info = ['']
|
| 79 |
+
if self._state is _State.ENTERED:
|
| 80 |
+
when = round(self._when, 3) if self._when is not None else None
|
| 81 |
+
info.append(f"when={when}")
|
| 82 |
+
info_str = ' '.join(info)
|
| 83 |
+
return f"<Timeout [{self._state.value}]{info_str}>"
|
| 84 |
+
|
| 85 |
+
async def __aenter__(self) -> "Timeout":
|
| 86 |
+
if self._state is not _State.CREATED:
|
| 87 |
+
raise RuntimeError("Timeout has already been entered")
|
| 88 |
+
task = tasks.current_task()
|
| 89 |
+
if task is None:
|
| 90 |
+
raise RuntimeError("Timeout should be used inside a task")
|
| 91 |
+
self._state = _State.ENTERED
|
| 92 |
+
self._task = task
|
| 93 |
+
self._cancelling = self._task.cancelling()
|
| 94 |
+
self.reschedule(self._when)
|
| 95 |
+
return self
|
| 96 |
+
|
| 97 |
+
async def __aexit__(
|
| 98 |
+
self,
|
| 99 |
+
exc_type: Optional[Type[BaseException]],
|
| 100 |
+
exc_val: Optional[BaseException],
|
| 101 |
+
exc_tb: Optional[TracebackType],
|
| 102 |
+
) -> Optional[bool]:
|
| 103 |
+
assert self._state in (_State.ENTERED, _State.EXPIRING)
|
| 104 |
+
|
| 105 |
+
if self._timeout_handler is not None:
|
| 106 |
+
self._timeout_handler.cancel()
|
| 107 |
+
self._timeout_handler = None
|
| 108 |
+
|
| 109 |
+
if self._state is _State.EXPIRING:
|
| 110 |
+
self._state = _State.EXPIRED
|
| 111 |
+
|
| 112 |
+
if self._task.uncancel() <= self._cancelling and exc_type is exceptions.CancelledError:
|
| 113 |
+
# Since there are no new cancel requests, we're
|
| 114 |
+
# handling this.
|
| 115 |
+
raise TimeoutError from exc_val
|
| 116 |
+
elif self._state is _State.ENTERED:
|
| 117 |
+
self._state = _State.EXITED
|
| 118 |
+
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
def _on_timeout(self) -> None:
|
| 122 |
+
assert self._state is _State.ENTERED
|
| 123 |
+
self._task.cancel()
|
| 124 |
+
self._state = _State.EXPIRING
|
| 125 |
+
# drop the reference early
|
| 126 |
+
self._timeout_handler = None
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def timeout(delay: Optional[float]) -> Timeout:
|
| 130 |
+
"""Timeout async context manager.
|
| 131 |
+
|
| 132 |
+
Useful in cases when you want to apply timeout logic around block
|
| 133 |
+
of code or in cases when asyncio.wait_for is not suitable. For example:
|
| 134 |
+
|
| 135 |
+
>>> async with asyncio.timeout(10): # 10 seconds timeout
|
| 136 |
+
... await long_running_task()
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
delay - value in seconds or None to disable timeout logic
|
| 140 |
+
|
| 141 |
+
long_running_task() is interrupted by raising asyncio.CancelledError,
|
| 142 |
+
the top-most affected timeout() context manager converts CancelledError
|
| 143 |
+
into TimeoutError.
|
| 144 |
+
"""
|
| 145 |
+
loop = events.get_running_loop()
|
| 146 |
+
return Timeout(loop.time() + delay if delay is not None else None)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def timeout_at(when: Optional[float]) -> Timeout:
|
| 150 |
+
"""Schedule the timeout at absolute time.
|
| 151 |
+
|
| 152 |
+
Like timeout() but argument gives absolute time in the same clock system
|
| 153 |
+
as loop.time().
|
| 154 |
+
|
| 155 |
+
Please note: it is not POSIX time but a time with
|
| 156 |
+
undefined starting base, e.g. the time of the system power on.
|
| 157 |
+
|
| 158 |
+
>>> async with asyncio.timeout_at(loop.time() + 10):
|
| 159 |
+
... await long_running_task()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
when - a deadline when timeout occurs or None to disable timeout logic
|
| 163 |
+
|
| 164 |
+
long_running_task() is interrupted by raising asyncio.CancelledError,
|
| 165 |
+
the top-most affected timeout() context manager converts CancelledError
|
| 166 |
+
into TimeoutError.
|
| 167 |
+
"""
|
| 168 |
+
return Timeout(when)
|
micromamba_root/envs/pytorch_env/Lib/asyncio/transports.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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"""Base class for transports."""
|
| 11 |
+
|
| 12 |
+
__slots__ = ('_extra',)
|
| 13 |
+
|
| 14 |
+
def __init__(self, extra=None):
|
| 15 |
+
if extra is None:
|
| 16 |
+
extra = {}
|
| 17 |
+
self._extra = extra
|
| 18 |
+
|
| 19 |
+
def get_extra_info(self, name, default=None):
|
| 20 |
+
"""Get optional transport information."""
|
| 21 |
+
return self._extra.get(name, default)
|
| 22 |
+
|
| 23 |
+
def is_closing(self):
|
| 24 |
+
"""Return True if the transport is closing or closed."""
|
| 25 |
+
raise NotImplementedError
|
| 26 |
+
|
| 27 |
+
def close(self):
|
| 28 |
+
"""Close the transport.
|
| 29 |
+
|
| 30 |
+
Buffered data will be flushed asynchronously. No more data
|
| 31 |
+
will be received. After all buffered data is flushed, the
|
| 32 |
+
protocol's connection_lost() method will (eventually) be
|
| 33 |
+
called with None as its argument.
|
| 34 |
+
"""
|
| 35 |
+
raise NotImplementedError
|
| 36 |
+
|
| 37 |
+
def set_protocol(self, protocol):
|
| 38 |
+
"""Set a new protocol."""
|
| 39 |
+
raise NotImplementedError
|
| 40 |
+
|
| 41 |
+
def get_protocol(self):
|
| 42 |
+
"""Return the current protocol."""
|
| 43 |
+
raise NotImplementedError
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class ReadTransport(BaseTransport):
|
| 47 |
+
"""Interface for read-only transports."""
|
| 48 |
+
|
| 49 |
+
__slots__ = ()
|
| 50 |
+
|
| 51 |
+
def is_reading(self):
|
| 52 |
+
"""Return True if the transport is receiving."""
|
| 53 |
+
raise NotImplementedError
|
| 54 |
+
|
| 55 |
+
def pause_reading(self):
|
| 56 |
+
"""Pause the receiving end.
|
| 57 |
+
|
| 58 |
+
No data will be passed to the protocol's data_received()
|
| 59 |
+
method until resume_reading() is called.
|
| 60 |
+
"""
|
| 61 |
+
raise NotImplementedError
|
| 62 |
+
|
| 63 |
+
def resume_reading(self):
|
| 64 |
+
"""Resume the receiving end.
|
| 65 |
+
|
| 66 |
+
Data received will once again be passed to the protocol's
|
| 67 |
+
data_received() method.
|
| 68 |
+
"""
|
| 69 |
+
raise NotImplementedError
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class WriteTransport(BaseTransport):
|
| 73 |
+
"""Interface for write-only transports."""
|
| 74 |
+
|
| 75 |
+
__slots__ = ()
|
| 76 |
+
|
| 77 |
+
def set_write_buffer_limits(self, high=None, low=None):
|
| 78 |
+
"""Set the high- and low-water limits for write flow control.
|
| 79 |
+
|
| 80 |
+
These two values control when to call the protocol's
|
| 81 |
+
pause_writing() and resume_writing() methods. If specified,
|
| 82 |
+
the low-water limit must be less than or equal to the
|
| 83 |
+
high-water limit. Neither value can be negative.
|
| 84 |
+
|
| 85 |
+
The defaults are implementation-specific. If only the
|
| 86 |
+
high-water limit is given, the low-water limit defaults to an
|
| 87 |
+
implementation-specific value less than or equal to the
|
| 88 |
+
high-water limit. Setting high to zero forces low to zero as
|
| 89 |
+
well, and causes pause_writing() to be called whenever the
|
| 90 |
+
buffer becomes non-empty. Setting low to zero causes
|
| 91 |
+
resume_writing() to be called only once the buffer is empty.
|
| 92 |
+
Use of zero for either limit is generally sub-optimal as it
|
| 93 |
+
reduces opportunities for doing I/O and computation
|
| 94 |
+
concurrently.
|
| 95 |
+
"""
|
| 96 |
+
raise NotImplementedError
|
| 97 |
+
|
| 98 |
+
def get_write_buffer_size(self):
|
| 99 |
+
"""Return the current size of the write buffer."""
|
| 100 |
+
raise NotImplementedError
|
| 101 |
+
|
| 102 |
+
def get_write_buffer_limits(self):
|
| 103 |
+
"""Get the high and low watermarks for write flow control.
|
| 104 |
+
Return a tuple (low, high) where low and high are
|
| 105 |
+
positive number of bytes."""
|
| 106 |
+
raise NotImplementedError
|
| 107 |
+
|
| 108 |
+
def write(self, data):
|
| 109 |
+
"""Write some data bytes to the transport.
|
| 110 |
+
|
| 111 |
+
This does not block; it buffers the data and arranges for it
|
| 112 |
+
to be sent out asynchronously.
|
| 113 |
+
"""
|
| 114 |
+
raise NotImplementedError
|
| 115 |
+
|
| 116 |
+
def writelines(self, list_of_data):
|
| 117 |
+
"""Write a list (or any iterable) of data bytes to the transport.
|
| 118 |
+
|
| 119 |
+
The default implementation concatenates the arguments and
|
| 120 |
+
calls write() on the result.
|
| 121 |
+
"""
|
| 122 |
+
data = b''.join(list_of_data)
|
| 123 |
+
self.write(data)
|
| 124 |
+
|
| 125 |
+
def write_eof(self):
|
| 126 |
+
"""Close the write end after flushing buffered data.
|
| 127 |
+
|
| 128 |
+
(This is like typing ^D into a UNIX program reading from stdin.)
|
| 129 |
+
|
| 130 |
+
Data may still be received.
|
| 131 |
+
"""
|
| 132 |
+
raise NotImplementedError
|
| 133 |
+
|
| 134 |
+
def can_write_eof(self):
|
| 135 |
+
"""Return True if this transport supports write_eof(), False if not."""
|
| 136 |
+
raise NotImplementedError
|
| 137 |
+
|
| 138 |
+
def abort(self):
|
| 139 |
+
"""Close the transport immediately.
|
| 140 |
+
|
| 141 |
+
Buffered data will be lost. No more data will be received.
|
| 142 |
+
The protocol's connection_lost() method will (eventually) be
|
| 143 |
+
called with None as its argument.
|
| 144 |
+
"""
|
| 145 |
+
raise NotImplementedError
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class Transport(ReadTransport, WriteTransport):
|
| 149 |
+
"""Interface representing a bidirectional transport.
|
| 150 |
+
|
| 151 |
+
There may be several implementations, but typically, the user does
|
| 152 |
+
not implement new transports; rather, the platform provides some
|
| 153 |
+
useful transports that are implemented using the platform's best
|
| 154 |
+
practices.
|
| 155 |
+
|
| 156 |
+
The user never instantiates a transport directly; they call a
|
| 157 |
+
utility function, passing it a protocol factory and other
|
| 158 |
+
information necessary to create the transport and protocol. (E.g.
|
| 159 |
+
EventLoop.create_connection() or EventLoop.create_server().)
|
| 160 |
+
|
| 161 |
+
The utility function will asynchronously create a transport and a
|
| 162 |
+
protocol and hook them up by calling the protocol's
|
| 163 |
+
connection_made() method, passing it the transport.
|
| 164 |
+
|
| 165 |
+
The implementation here raises NotImplemented for every method
|
| 166 |
+
except writelines(), which calls write() in a loop.
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
__slots__ = ()
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class DatagramTransport(BaseTransport):
|
| 173 |
+
"""Interface for datagram (UDP) transports."""
|
| 174 |
+
|
| 175 |
+
__slots__ = ()
|
| 176 |
+
|
| 177 |
+
def sendto(self, data, addr=None):
|
| 178 |
+
"""Send data to the transport.
|
| 179 |
+
|
| 180 |
+
This does not block; it buffers the data and arranges for it
|
| 181 |
+
to be sent out asynchronously.
|
| 182 |
+
addr is target socket address.
|
| 183 |
+
If addr is None use target address pointed on transport creation.
|
| 184 |
+
"""
|
| 185 |
+
raise NotImplementedError
|
| 186 |
+
|
| 187 |
+
def abort(self):
|
| 188 |
+
"""Close the transport immediately.
|
| 189 |
+
|
| 190 |
+
Buffered data will be lost. No more data will be received.
|
| 191 |
+
The protocol's connection_lost() method will (eventually) be
|
| 192 |
+
called with None as its argument.
|
| 193 |
+
"""
|
| 194 |
+
raise NotImplementedError
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class SubprocessTransport(BaseTransport):
|
| 198 |
+
|
| 199 |
+
__slots__ = ()
|
| 200 |
+
|
| 201 |
+
def get_pid(self):
|
| 202 |
+
"""Get subprocess id."""
|
| 203 |
+
raise NotImplementedError
|
| 204 |
+
|
| 205 |
+
def get_returncode(self):
|
| 206 |
+
"""Get subprocess returncode.
|
| 207 |
+
|
| 208 |
+
See also
|
| 209 |
+
http://docs.python.org/3/library/subprocess#subprocess.Popen.returncode
|
| 210 |
+
"""
|
| 211 |
+
raise NotImplementedError
|
| 212 |
+
|
| 213 |
+
def get_pipe_transport(self, fd):
|
| 214 |
+
"""Get transport for pipe with number fd."""
|
| 215 |
+
raise NotImplementedError
|
| 216 |
+
|
| 217 |
+
def send_signal(self, signal):
|
| 218 |
+
"""Send signal to subprocess.
|
| 219 |
+
|
| 220 |
+
See also:
|
| 221 |
+
docs.python.org/3/library/subprocess#subprocess.Popen.send_signal
|
| 222 |
+
"""
|
| 223 |
+
raise NotImplementedError
|
| 224 |
+
|
| 225 |
+
def terminate(self):
|
| 226 |
+
"""Stop the subprocess.
|
| 227 |
+
|
| 228 |
+
Alias for close() method.
|
| 229 |
+
|
| 230 |
+
On Posix OSs the method sends SIGTERM to the subprocess.
|
| 231 |
+
On Windows the Win32 API function TerminateProcess()
|
| 232 |
+
is called to stop the subprocess.
|
| 233 |
+
|
| 234 |
+
See also:
|
| 235 |
+
http://docs.python.org/3/library/subprocess#subprocess.Popen.terminate
|
| 236 |
+
"""
|
| 237 |
+
raise NotImplementedError
|
| 238 |
+
|
| 239 |
+
def kill(self):
|
| 240 |
+
"""Kill the subprocess.
|
| 241 |
+
|
| 242 |
+
On Posix OSs the function sends SIGKILL to the subprocess.
|
| 243 |
+
On Windows kill() is an alias for terminate().
|
| 244 |
+
|
| 245 |
+
See also:
|
| 246 |
+
http://docs.python.org/3/library/subprocess#subprocess.Popen.kill
|
| 247 |
+
"""
|
| 248 |
+
raise NotImplementedError
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class _FlowControlMixin(Transport):
|
| 252 |
+
"""All the logic for (write) flow control in a mix-in base class.
|
| 253 |
+
|
| 254 |
+
The subclass must implement get_write_buffer_size(). It must call
|
| 255 |
+
_maybe_pause_protocol() whenever the write buffer size increases,
|
| 256 |
+
and _maybe_resume_protocol() whenever it decreases. It may also
|
| 257 |
+
override set_write_buffer_limits() (e.g. to specify different
|
| 258 |
+
defaults).
|
| 259 |
+
|
| 260 |
+
The subclass constructor must call super().__init__(extra). This
|
| 261 |
+
will call set_write_buffer_limits().
|
| 262 |
+
|
| 263 |
+
The user may call set_write_buffer_limits() and
|
| 264 |
+
get_write_buffer_size(), and their protocol's pause_writing() and
|
| 265 |
+
resume_writing() may be called.
|
| 266 |
+
"""
|
| 267 |
+
|
| 268 |
+
__slots__ = ('_loop', '_protocol_paused', '_high_water', '_low_water')
|
| 269 |
+
|
| 270 |
+
def __init__(self, extra=None, loop=None):
|
| 271 |
+
super().__init__(extra)
|
| 272 |
+
assert loop is not None
|
| 273 |
+
self._loop = loop
|
| 274 |
+
self._protocol_paused = False
|
| 275 |
+
self._set_write_buffer_limits()
|
| 276 |
+
|
| 277 |
+
def _maybe_pause_protocol(self):
|
| 278 |
+
size = self.get_write_buffer_size()
|
| 279 |
+
if size <= self._high_water:
|
| 280 |
+
return
|
| 281 |
+
if not self._protocol_paused:
|
| 282 |
+
self._protocol_paused = True
|
| 283 |
+
try:
|
| 284 |
+
self._protocol.pause_writing()
|
| 285 |
+
except (SystemExit, KeyboardInterrupt):
|
| 286 |
+
raise
|
| 287 |
+
except BaseException as exc:
|
| 288 |
+
self._loop.call_exception_handler({
|
| 289 |
+
'message': 'protocol.pause_writing() failed',
|
| 290 |
+
'exception': exc,
|
| 291 |
+
'transport': self,
|
| 292 |
+
'protocol': self._protocol,
|
| 293 |
+
})
|
| 294 |
+
|
| 295 |
+
def _maybe_resume_protocol(self):
|
| 296 |
+
if (self._protocol_paused and
|
| 297 |
+
self.get_write_buffer_size() <= self._low_water):
|
| 298 |
+
self._protocol_paused = False
|
| 299 |
+
try:
|
| 300 |
+
self._protocol.resume_writing()
|
| 301 |
+
except (SystemExit, KeyboardInterrupt):
|
| 302 |
+
raise
|
| 303 |
+
except BaseException as exc:
|
| 304 |
+
self._loop.call_exception_handler({
|
| 305 |
+
'message': 'protocol.resume_writing() failed',
|
| 306 |
+
'exception': exc,
|
| 307 |
+
'transport': self,
|
| 308 |
+
'protocol': self._protocol,
|
| 309 |
+
})
|
| 310 |
+
|
| 311 |
+
def get_write_buffer_limits(self):
|
| 312 |
+
return (self._low_water, self._high_water)
|
| 313 |
+
|
| 314 |
+
def _set_write_buffer_limits(self, high=None, low=None):
|
| 315 |
+
if high is None:
|
| 316 |
+
if low is None:
|
| 317 |
+
high = 64 * 1024
|
| 318 |
+
else:
|
| 319 |
+
high = 4 * low
|
| 320 |
+
if low is None:
|
| 321 |
+
low = high // 4
|
| 322 |
+
|
| 323 |
+
if not high >= low >= 0:
|
| 324 |
+
raise ValueError(
|
| 325 |
+
f'high ({high!r}) must be >= low ({low!r}) must be >= 0')
|
| 326 |
+
|
| 327 |
+
self._high_water = high
|
| 328 |
+
self._low_water = low
|
| 329 |
+
|
| 330 |
+
def set_write_buffer_limits(self, high=None, low=None):
|
| 331 |
+
self._set_write_buffer_limits(high=high, low=low)
|
| 332 |
+
self._maybe_pause_protocol()
|
| 333 |
+
|
| 334 |
+
def get_write_buffer_size(self):
|
| 335 |
+
raise NotImplementedError
|
micromamba_root/envs/pytorch_env/Lib/asyncio/trsock.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import socket
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class TransportSocket:
|
| 5 |
+
|
| 6 |
+
"""A socket-like wrapper for exposing real transport sockets.
|
| 7 |
+
|
| 8 |
+
These objects can be safely returned by APIs like
|
| 9 |
+
`transport.get_extra_info('socket')`. All potentially disruptive
|
| 10 |
+
operations (like "socket.close()") are banned.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
__slots__ = ('_sock',)
|
| 14 |
+
|
| 15 |
+
def __init__(self, sock: socket.socket):
|
| 16 |
+
self._sock = sock
|
| 17 |
+
|
| 18 |
+
@property
|
| 19 |
+
def family(self):
|
| 20 |
+
return self._sock.family
|
| 21 |
+
|
| 22 |
+
@property
|
| 23 |
+
def type(self):
|
| 24 |
+
return self._sock.type
|
| 25 |
+
|
| 26 |
+
@property
|
| 27 |
+
def proto(self):
|
| 28 |
+
return self._sock.proto
|
| 29 |
+
|
| 30 |
+
def __repr__(self):
|
| 31 |
+
s = (
|
| 32 |
+
f"<asyncio.TransportSocket fd={self.fileno()}, "
|
| 33 |
+
f"family={self.family!s}, type={self.type!s}, "
|
| 34 |
+
f"proto={self.proto}"
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
if self.fileno() != -1:
|
| 38 |
+
try:
|
| 39 |
+
laddr = self.getsockname()
|
| 40 |
+
if laddr:
|
| 41 |
+
s = f"{s}, laddr={laddr}"
|
| 42 |
+
except socket.error:
|
| 43 |
+
pass
|
| 44 |
+
try:
|
| 45 |
+
raddr = self.getpeername()
|
| 46 |
+
if raddr:
|
| 47 |
+
s = f"{s}, raddr={raddr}"
|
| 48 |
+
except socket.error:
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
return f"{s}>"
|
| 52 |
+
|
| 53 |
+
def __getstate__(self):
|
| 54 |
+
raise TypeError("Cannot serialize asyncio.TransportSocket object")
|
| 55 |
+
|
| 56 |
+
def fileno(self):
|
| 57 |
+
return self._sock.fileno()
|
| 58 |
+
|
| 59 |
+
def dup(self):
|
| 60 |
+
return self._sock.dup()
|
| 61 |
+
|
| 62 |
+
def get_inheritable(self):
|
| 63 |
+
return self._sock.get_inheritable()
|
| 64 |
+
|
| 65 |
+
def shutdown(self, how):
|
| 66 |
+
# asyncio doesn't currently provide a high-level transport API
|
| 67 |
+
# to shutdown the connection.
|
| 68 |
+
self._sock.shutdown(how)
|
| 69 |
+
|
| 70 |
+
def getsockopt(self, *args, **kwargs):
|
| 71 |
+
return self._sock.getsockopt(*args, **kwargs)
|
| 72 |
+
|
| 73 |
+
def setsockopt(self, *args, **kwargs):
|
| 74 |
+
self._sock.setsockopt(*args, **kwargs)
|
| 75 |
+
|
| 76 |
+
def getpeername(self):
|
| 77 |
+
return self._sock.getpeername()
|
| 78 |
+
|
| 79 |
+
def getsockname(self):
|
| 80 |
+
return self._sock.getsockname()
|
| 81 |
+
|
| 82 |
+
def getsockbyname(self):
|
| 83 |
+
return self._sock.getsockbyname()
|
| 84 |
+
|
| 85 |
+
def settimeout(self, value):
|
| 86 |
+
if value == 0:
|
| 87 |
+
return
|
| 88 |
+
raise ValueError(
|
| 89 |
+
'settimeout(): only 0 timeout is allowed on transport sockets')
|
| 90 |
+
|
| 91 |
+
def gettimeout(self):
|
| 92 |
+
return 0
|
| 93 |
+
|
| 94 |
+
def setblocking(self, flag):
|
| 95 |
+
if not flag:
|
| 96 |
+
return
|
| 97 |
+
raise ValueError(
|
| 98 |
+
'setblocking(): transport sockets cannot be blocking')
|
micromamba_root/envs/pytorch_env/Lib/asyncio/unix_events.py
ADDED
|
@@ -0,0 +1,1476 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Selector event loop for Unix with signal handling."""
|
| 2 |
+
|
| 3 |
+
import errno
|
| 4 |
+
import io
|
| 5 |
+
import itertools
|
| 6 |
+
import os
|
| 7 |
+
import selectors
|
| 8 |
+
import signal
|
| 9 |
+
import socket
|
| 10 |
+
import stat
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import threading
|
| 14 |
+
import warnings
|
| 15 |
+
|
| 16 |
+
from . import base_events
|
| 17 |
+
from . import base_subprocess
|
| 18 |
+
from . import constants
|
| 19 |
+
from . import coroutines
|
| 20 |
+
from . import events
|
| 21 |
+
from . import exceptions
|
| 22 |
+
from . import futures
|
| 23 |
+
from . import selector_events
|
| 24 |
+
from . import tasks
|
| 25 |
+
from . import transports
|
| 26 |
+
from .log import logger
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
__all__ = (
|
| 30 |
+
'SelectorEventLoop',
|
| 31 |
+
'AbstractChildWatcher', 'SafeChildWatcher',
|
| 32 |
+
'FastChildWatcher', 'PidfdChildWatcher',
|
| 33 |
+
'MultiLoopChildWatcher', 'ThreadedChildWatcher',
|
| 34 |
+
'DefaultEventLoopPolicy',
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if sys.platform == 'win32': # pragma: no cover
|
| 39 |
+
raise ImportError('Signals are not really supported on Windows')
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _sighandler_noop(signum, frame):
|
| 43 |
+
"""Dummy signal handler."""
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def waitstatus_to_exitcode(status):
|
| 48 |
+
try:
|
| 49 |
+
return os.waitstatus_to_exitcode(status)
|
| 50 |
+
except ValueError:
|
| 51 |
+
# The child exited, but we don't understand its status.
|
| 52 |
+
# This shouldn't happen, but if it does, let's just
|
| 53 |
+
# return that status; perhaps that helps debug it.
|
| 54 |
+
return status
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
|
| 58 |
+
"""Unix event loop.
|
| 59 |
+
|
| 60 |
+
Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
def __init__(self, selector=None):
|
| 64 |
+
super().__init__(selector)
|
| 65 |
+
self._signal_handlers = {}
|
| 66 |
+
|
| 67 |
+
def close(self):
|
| 68 |
+
super().close()
|
| 69 |
+
if not sys.is_finalizing():
|
| 70 |
+
for sig in list(self._signal_handlers):
|
| 71 |
+
self.remove_signal_handler(sig)
|
| 72 |
+
else:
|
| 73 |
+
if self._signal_handlers:
|
| 74 |
+
warnings.warn(f"Closing the loop {self!r} "
|
| 75 |
+
f"on interpreter shutdown "
|
| 76 |
+
f"stage, skipping signal handlers removal",
|
| 77 |
+
ResourceWarning,
|
| 78 |
+
source=self)
|
| 79 |
+
self._signal_handlers.clear()
|
| 80 |
+
|
| 81 |
+
def _process_self_data(self, data):
|
| 82 |
+
for signum in data:
|
| 83 |
+
if not signum:
|
| 84 |
+
# ignore null bytes written by _write_to_self()
|
| 85 |
+
continue
|
| 86 |
+
self._handle_signal(signum)
|
| 87 |
+
|
| 88 |
+
def add_signal_handler(self, sig, callback, *args):
|
| 89 |
+
"""Add a handler for a signal. UNIX only.
|
| 90 |
+
|
| 91 |
+
Raise ValueError if the signal number is invalid or uncatchable.
|
| 92 |
+
Raise RuntimeError if there is a problem setting up the handler.
|
| 93 |
+
"""
|
| 94 |
+
if (coroutines.iscoroutine(callback) or
|
| 95 |
+
coroutines.iscoroutinefunction(callback)):
|
| 96 |
+
raise TypeError("coroutines cannot be used "
|
| 97 |
+
"with add_signal_handler()")
|
| 98 |
+
self._check_signal(sig)
|
| 99 |
+
self._check_closed()
|
| 100 |
+
try:
|
| 101 |
+
# set_wakeup_fd() raises ValueError if this is not the
|
| 102 |
+
# main thread. By calling it early we ensure that an
|
| 103 |
+
# event loop running in another thread cannot add a signal
|
| 104 |
+
# handler.
|
| 105 |
+
signal.set_wakeup_fd(self._csock.fileno())
|
| 106 |
+
except (ValueError, OSError) as exc:
|
| 107 |
+
raise RuntimeError(str(exc))
|
| 108 |
+
|
| 109 |
+
handle = events.Handle(callback, args, self, None)
|
| 110 |
+
self._signal_handlers[sig] = handle
|
| 111 |
+
|
| 112 |
+
try:
|
| 113 |
+
# Register a dummy signal handler to ask Python to write the signal
|
| 114 |
+
# number in the wakeup file descriptor. _process_self_data() will
|
| 115 |
+
# read signal numbers from this file descriptor to handle signals.
|
| 116 |
+
signal.signal(sig, _sighandler_noop)
|
| 117 |
+
|
| 118 |
+
# Set SA_RESTART to limit EINTR occurrences.
|
| 119 |
+
signal.siginterrupt(sig, False)
|
| 120 |
+
except OSError as exc:
|
| 121 |
+
del self._signal_handlers[sig]
|
| 122 |
+
if not self._signal_handlers:
|
| 123 |
+
try:
|
| 124 |
+
signal.set_wakeup_fd(-1)
|
| 125 |
+
except (ValueError, OSError) as nexc:
|
| 126 |
+
logger.info('set_wakeup_fd(-1) failed: %s', nexc)
|
| 127 |
+
|
| 128 |
+
if exc.errno == errno.EINVAL:
|
| 129 |
+
raise RuntimeError(f'sig {sig} cannot be caught')
|
| 130 |
+
else:
|
| 131 |
+
raise
|
| 132 |
+
|
| 133 |
+
def _handle_signal(self, sig):
|
| 134 |
+
"""Internal helper that is the actual signal handler."""
|
| 135 |
+
handle = self._signal_handlers.get(sig)
|
| 136 |
+
if handle is None:
|
| 137 |
+
return # Assume it's some race condition.
|
| 138 |
+
if handle._cancelled:
|
| 139 |
+
self.remove_signal_handler(sig) # Remove it properly.
|
| 140 |
+
else:
|
| 141 |
+
self._add_callback_signalsafe(handle)
|
| 142 |
+
|
| 143 |
+
def remove_signal_handler(self, sig):
|
| 144 |
+
"""Remove a handler for a signal. UNIX only.
|
| 145 |
+
|
| 146 |
+
Return True if a signal handler was removed, False if not.
|
| 147 |
+
"""
|
| 148 |
+
self._check_signal(sig)
|
| 149 |
+
try:
|
| 150 |
+
del self._signal_handlers[sig]
|
| 151 |
+
except KeyError:
|
| 152 |
+
return False
|
| 153 |
+
|
| 154 |
+
if sig == signal.SIGINT:
|
| 155 |
+
handler = signal.default_int_handler
|
| 156 |
+
else:
|
| 157 |
+
handler = signal.SIG_DFL
|
| 158 |
+
|
| 159 |
+
try:
|
| 160 |
+
signal.signal(sig, handler)
|
| 161 |
+
except OSError as exc:
|
| 162 |
+
if exc.errno == errno.EINVAL:
|
| 163 |
+
raise RuntimeError(f'sig {sig} cannot be caught')
|
| 164 |
+
else:
|
| 165 |
+
raise
|
| 166 |
+
|
| 167 |
+
if not self._signal_handlers:
|
| 168 |
+
try:
|
| 169 |
+
signal.set_wakeup_fd(-1)
|
| 170 |
+
except (ValueError, OSError) as exc:
|
| 171 |
+
logger.info('set_wakeup_fd(-1) failed: %s', exc)
|
| 172 |
+
|
| 173 |
+
return True
|
| 174 |
+
|
| 175 |
+
def _check_signal(self, sig):
|
| 176 |
+
"""Internal helper to validate a signal.
|
| 177 |
+
|
| 178 |
+
Raise ValueError if the signal number is invalid or uncatchable.
|
| 179 |
+
Raise RuntimeError if there is a problem setting up the handler.
|
| 180 |
+
"""
|
| 181 |
+
if not isinstance(sig, int):
|
| 182 |
+
raise TypeError(f'sig must be an int, not {sig!r}')
|
| 183 |
+
|
| 184 |
+
if sig not in signal.valid_signals():
|
| 185 |
+
raise ValueError(f'invalid signal number {sig}')
|
| 186 |
+
|
| 187 |
+
def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
|
| 188 |
+
extra=None):
|
| 189 |
+
return _UnixReadPipeTransport(self, pipe, protocol, waiter, extra)
|
| 190 |
+
|
| 191 |
+
def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
|
| 192 |
+
extra=None):
|
| 193 |
+
return _UnixWritePipeTransport(self, pipe, protocol, waiter, extra)
|
| 194 |
+
|
| 195 |
+
async def _make_subprocess_transport(self, protocol, args, shell,
|
| 196 |
+
stdin, stdout, stderr, bufsize,
|
| 197 |
+
extra=None, **kwargs):
|
| 198 |
+
with events.get_child_watcher() as watcher:
|
| 199 |
+
if not watcher.is_active():
|
| 200 |
+
# Check early.
|
| 201 |
+
# Raising exception before process creation
|
| 202 |
+
# prevents subprocess execution if the watcher
|
| 203 |
+
# is not ready to handle it.
|
| 204 |
+
raise RuntimeError("asyncio.get_child_watcher() is not activated, "
|
| 205 |
+
"subprocess support is not installed.")
|
| 206 |
+
waiter = self.create_future()
|
| 207 |
+
transp = _UnixSubprocessTransport(self, protocol, args, shell,
|
| 208 |
+
stdin, stdout, stderr, bufsize,
|
| 209 |
+
waiter=waiter, extra=extra,
|
| 210 |
+
**kwargs)
|
| 211 |
+
|
| 212 |
+
watcher.add_child_handler(transp.get_pid(),
|
| 213 |
+
self._child_watcher_callback, transp)
|
| 214 |
+
try:
|
| 215 |
+
await waiter
|
| 216 |
+
except (SystemExit, KeyboardInterrupt):
|
| 217 |
+
raise
|
| 218 |
+
except BaseException:
|
| 219 |
+
transp.close()
|
| 220 |
+
await transp._wait()
|
| 221 |
+
raise
|
| 222 |
+
|
| 223 |
+
return transp
|
| 224 |
+
|
| 225 |
+
def _child_watcher_callback(self, pid, returncode, transp):
|
| 226 |
+
# Skip one iteration for callbacks to be executed
|
| 227 |
+
self.call_soon_threadsafe(self.call_soon, transp._process_exited, returncode)
|
| 228 |
+
|
| 229 |
+
async def create_unix_connection(
|
| 230 |
+
self, protocol_factory, path=None, *,
|
| 231 |
+
ssl=None, sock=None,
|
| 232 |
+
server_hostname=None,
|
| 233 |
+
ssl_handshake_timeout=None,
|
| 234 |
+
ssl_shutdown_timeout=None):
|
| 235 |
+
assert server_hostname is None or isinstance(server_hostname, str)
|
| 236 |
+
if ssl:
|
| 237 |
+
if server_hostname is None:
|
| 238 |
+
raise ValueError(
|
| 239 |
+
'you have to pass server_hostname when using ssl')
|
| 240 |
+
else:
|
| 241 |
+
if server_hostname is not None:
|
| 242 |
+
raise ValueError('server_hostname is only meaningful with ssl')
|
| 243 |
+
if ssl_handshake_timeout is not None:
|
| 244 |
+
raise ValueError(
|
| 245 |
+
'ssl_handshake_timeout is only meaningful with ssl')
|
| 246 |
+
if ssl_shutdown_timeout is not None:
|
| 247 |
+
raise ValueError(
|
| 248 |
+
'ssl_shutdown_timeout is only meaningful with ssl')
|
| 249 |
+
|
| 250 |
+
if path is not None:
|
| 251 |
+
if sock is not None:
|
| 252 |
+
raise ValueError(
|
| 253 |
+
'path and sock can not be specified at the same time')
|
| 254 |
+
|
| 255 |
+
path = os.fspath(path)
|
| 256 |
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
|
| 257 |
+
try:
|
| 258 |
+
sock.setblocking(False)
|
| 259 |
+
await self.sock_connect(sock, path)
|
| 260 |
+
except:
|
| 261 |
+
sock.close()
|
| 262 |
+
raise
|
| 263 |
+
|
| 264 |
+
else:
|
| 265 |
+
if sock is None:
|
| 266 |
+
raise ValueError('no path and sock were specified')
|
| 267 |
+
if (sock.family != socket.AF_UNIX or
|
| 268 |
+
sock.type != socket.SOCK_STREAM):
|
| 269 |
+
raise ValueError(
|
| 270 |
+
f'A UNIX Domain Stream Socket was expected, got {sock!r}')
|
| 271 |
+
sock.setblocking(False)
|
| 272 |
+
|
| 273 |
+
transport, protocol = await self._create_connection_transport(
|
| 274 |
+
sock, protocol_factory, ssl, server_hostname,
|
| 275 |
+
ssl_handshake_timeout=ssl_handshake_timeout,
|
| 276 |
+
ssl_shutdown_timeout=ssl_shutdown_timeout)
|
| 277 |
+
return transport, protocol
|
| 278 |
+
|
| 279 |
+
async def create_unix_server(
|
| 280 |
+
self, protocol_factory, path=None, *,
|
| 281 |
+
sock=None, backlog=100, ssl=None,
|
| 282 |
+
ssl_handshake_timeout=None,
|
| 283 |
+
ssl_shutdown_timeout=None,
|
| 284 |
+
start_serving=True):
|
| 285 |
+
if isinstance(ssl, bool):
|
| 286 |
+
raise TypeError('ssl argument must be an SSLContext or None')
|
| 287 |
+
|
| 288 |
+
if ssl_handshake_timeout is not None and not ssl:
|
| 289 |
+
raise ValueError(
|
| 290 |
+
'ssl_handshake_timeout is only meaningful with ssl')
|
| 291 |
+
|
| 292 |
+
if ssl_shutdown_timeout is not None and not ssl:
|
| 293 |
+
raise ValueError(
|
| 294 |
+
'ssl_shutdown_timeout is only meaningful with ssl')
|
| 295 |
+
|
| 296 |
+
if path is not None:
|
| 297 |
+
if sock is not None:
|
| 298 |
+
raise ValueError(
|
| 299 |
+
'path and sock can not be specified at the same time')
|
| 300 |
+
|
| 301 |
+
path = os.fspath(path)
|
| 302 |
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
| 303 |
+
|
| 304 |
+
# Check for abstract socket. `str` and `bytes` paths are supported.
|
| 305 |
+
if path[0] not in (0, '\x00'):
|
| 306 |
+
try:
|
| 307 |
+
if stat.S_ISSOCK(os.stat(path).st_mode):
|
| 308 |
+
os.remove(path)
|
| 309 |
+
except FileNotFoundError:
|
| 310 |
+
pass
|
| 311 |
+
except OSError as err:
|
| 312 |
+
# Directory may have permissions only to create socket.
|
| 313 |
+
logger.error('Unable to check or remove stale UNIX socket '
|
| 314 |
+
'%r: %r', path, err)
|
| 315 |
+
|
| 316 |
+
try:
|
| 317 |
+
sock.bind(path)
|
| 318 |
+
except OSError as exc:
|
| 319 |
+
sock.close()
|
| 320 |
+
if exc.errno == errno.EADDRINUSE:
|
| 321 |
+
# Let's improve the error message by adding
|
| 322 |
+
# with what exact address it occurs.
|
| 323 |
+
msg = f'Address {path!r} is already in use'
|
| 324 |
+
raise OSError(errno.EADDRINUSE, msg) from None
|
| 325 |
+
else:
|
| 326 |
+
raise
|
| 327 |
+
except:
|
| 328 |
+
sock.close()
|
| 329 |
+
raise
|
| 330 |
+
else:
|
| 331 |
+
if sock is None:
|
| 332 |
+
raise ValueError(
|
| 333 |
+
'path was not specified, and no sock specified')
|
| 334 |
+
|
| 335 |
+
if (sock.family != socket.AF_UNIX or
|
| 336 |
+
sock.type != socket.SOCK_STREAM):
|
| 337 |
+
raise ValueError(
|
| 338 |
+
f'A UNIX Domain Stream Socket was expected, got {sock!r}')
|
| 339 |
+
|
| 340 |
+
sock.setblocking(False)
|
| 341 |
+
server = base_events.Server(self, [sock], protocol_factory,
|
| 342 |
+
ssl, backlog, ssl_handshake_timeout,
|
| 343 |
+
ssl_shutdown_timeout)
|
| 344 |
+
if start_serving:
|
| 345 |
+
server._start_serving()
|
| 346 |
+
# Skip one loop iteration so that all 'loop.add_reader'
|
| 347 |
+
# go through.
|
| 348 |
+
await tasks.sleep(0)
|
| 349 |
+
|
| 350 |
+
return server
|
| 351 |
+
|
| 352 |
+
async def _sock_sendfile_native(self, sock, file, offset, count):
|
| 353 |
+
try:
|
| 354 |
+
os.sendfile
|
| 355 |
+
except AttributeError:
|
| 356 |
+
raise exceptions.SendfileNotAvailableError(
|
| 357 |
+
"os.sendfile() is not available")
|
| 358 |
+
try:
|
| 359 |
+
fileno = file.fileno()
|
| 360 |
+
except (AttributeError, io.UnsupportedOperation) as err:
|
| 361 |
+
raise exceptions.SendfileNotAvailableError("not a regular file")
|
| 362 |
+
try:
|
| 363 |
+
fsize = os.fstat(fileno).st_size
|
| 364 |
+
except OSError:
|
| 365 |
+
raise exceptions.SendfileNotAvailableError("not a regular file")
|
| 366 |
+
blocksize = count if count else fsize
|
| 367 |
+
if not blocksize:
|
| 368 |
+
return 0 # empty file
|
| 369 |
+
|
| 370 |
+
fut = self.create_future()
|
| 371 |
+
self._sock_sendfile_native_impl(fut, None, sock, fileno,
|
| 372 |
+
offset, count, blocksize, 0)
|
| 373 |
+
return await fut
|
| 374 |
+
|
| 375 |
+
def _sock_sendfile_native_impl(self, fut, registered_fd, sock, fileno,
|
| 376 |
+
offset, count, blocksize, total_sent):
|
| 377 |
+
fd = sock.fileno()
|
| 378 |
+
if registered_fd is not None:
|
| 379 |
+
# Remove the callback early. It should be rare that the
|
| 380 |
+
# selector says the fd is ready but the call still returns
|
| 381 |
+
# EAGAIN, and I am willing to take a hit in that case in
|
| 382 |
+
# order to simplify the common case.
|
| 383 |
+
self.remove_writer(registered_fd)
|
| 384 |
+
if fut.cancelled():
|
| 385 |
+
self._sock_sendfile_update_filepos(fileno, offset, total_sent)
|
| 386 |
+
return
|
| 387 |
+
if count:
|
| 388 |
+
blocksize = count - total_sent
|
| 389 |
+
if blocksize <= 0:
|
| 390 |
+
self._sock_sendfile_update_filepos(fileno, offset, total_sent)
|
| 391 |
+
fut.set_result(total_sent)
|
| 392 |
+
return
|
| 393 |
+
|
| 394 |
+
try:
|
| 395 |
+
sent = os.sendfile(fd, fileno, offset, blocksize)
|
| 396 |
+
except (BlockingIOError, InterruptedError):
|
| 397 |
+
if registered_fd is None:
|
| 398 |
+
self._sock_add_cancellation_callback(fut, sock)
|
| 399 |
+
self.add_writer(fd, self._sock_sendfile_native_impl, fut,
|
| 400 |
+
fd, sock, fileno,
|
| 401 |
+
offset, count, blocksize, total_sent)
|
| 402 |
+
except OSError as exc:
|
| 403 |
+
if (registered_fd is not None and
|
| 404 |
+
exc.errno == errno.ENOTCONN and
|
| 405 |
+
type(exc) is not ConnectionError):
|
| 406 |
+
# If we have an ENOTCONN and this isn't a first call to
|
| 407 |
+
# sendfile(), i.e. the connection was closed in the middle
|
| 408 |
+
# of the operation, normalize the error to ConnectionError
|
| 409 |
+
# to make it consistent across all Posix systems.
|
| 410 |
+
new_exc = ConnectionError(
|
| 411 |
+
"socket is not connected", errno.ENOTCONN)
|
| 412 |
+
new_exc.__cause__ = exc
|
| 413 |
+
exc = new_exc
|
| 414 |
+
if total_sent == 0:
|
| 415 |
+
# We can get here for different reasons, the main
|
| 416 |
+
# one being 'file' is not a regular mmap(2)-like
|
| 417 |
+
# file, in which case we'll fall back on using
|
| 418 |
+
# plain send().
|
| 419 |
+
err = exceptions.SendfileNotAvailableError(
|
| 420 |
+
"os.sendfile call failed")
|
| 421 |
+
self._sock_sendfile_update_filepos(fileno, offset, total_sent)
|
| 422 |
+
fut.set_exception(err)
|
| 423 |
+
else:
|
| 424 |
+
self._sock_sendfile_update_filepos(fileno, offset, total_sent)
|
| 425 |
+
fut.set_exception(exc)
|
| 426 |
+
except (SystemExit, KeyboardInterrupt):
|
| 427 |
+
raise
|
| 428 |
+
except BaseException as exc:
|
| 429 |
+
self._sock_sendfile_update_filepos(fileno, offset, total_sent)
|
| 430 |
+
fut.set_exception(exc)
|
| 431 |
+
else:
|
| 432 |
+
if sent == 0:
|
| 433 |
+
# EOF
|
| 434 |
+
self._sock_sendfile_update_filepos(fileno, offset, total_sent)
|
| 435 |
+
fut.set_result(total_sent)
|
| 436 |
+
else:
|
| 437 |
+
offset += sent
|
| 438 |
+
total_sent += sent
|
| 439 |
+
if registered_fd is None:
|
| 440 |
+
self._sock_add_cancellation_callback(fut, sock)
|
| 441 |
+
self.add_writer(fd, self._sock_sendfile_native_impl, fut,
|
| 442 |
+
fd, sock, fileno,
|
| 443 |
+
offset, count, blocksize, total_sent)
|
| 444 |
+
|
| 445 |
+
def _sock_sendfile_update_filepos(self, fileno, offset, total_sent):
|
| 446 |
+
if total_sent > 0:
|
| 447 |
+
os.lseek(fileno, offset, os.SEEK_SET)
|
| 448 |
+
|
| 449 |
+
def _sock_add_cancellation_callback(self, fut, sock):
|
| 450 |
+
def cb(fut):
|
| 451 |
+
if fut.cancelled():
|
| 452 |
+
fd = sock.fileno()
|
| 453 |
+
if fd != -1:
|
| 454 |
+
self.remove_writer(fd)
|
| 455 |
+
fut.add_done_callback(cb)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class _UnixReadPipeTransport(transports.ReadTransport):
|
| 459 |
+
|
| 460 |
+
max_size = 256 * 1024 # max bytes we read in one event loop iteration
|
| 461 |
+
|
| 462 |
+
def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
|
| 463 |
+
super().__init__(extra)
|
| 464 |
+
self._extra['pipe'] = pipe
|
| 465 |
+
self._loop = loop
|
| 466 |
+
self._pipe = pipe
|
| 467 |
+
self._fileno = pipe.fileno()
|
| 468 |
+
self._protocol = protocol
|
| 469 |
+
self._closing = False
|
| 470 |
+
self._paused = False
|
| 471 |
+
|
| 472 |
+
mode = os.fstat(self._fileno).st_mode
|
| 473 |
+
if not (stat.S_ISFIFO(mode) or
|
| 474 |
+
stat.S_ISSOCK(mode) or
|
| 475 |
+
stat.S_ISCHR(mode)):
|
| 476 |
+
self._pipe = None
|
| 477 |
+
self._fileno = None
|
| 478 |
+
self._protocol = None
|
| 479 |
+
raise ValueError("Pipe transport is for pipes/sockets only.")
|
| 480 |
+
|
| 481 |
+
os.set_blocking(self._fileno, False)
|
| 482 |
+
|
| 483 |
+
self._loop.call_soon(self._protocol.connection_made, self)
|
| 484 |
+
# only start reading when connection_made() has been called
|
| 485 |
+
self._loop.call_soon(self._add_reader,
|
| 486 |
+
self._fileno, self._read_ready)
|
| 487 |
+
if waiter is not None:
|
| 488 |
+
# only wake up the waiter when connection_made() has been called
|
| 489 |
+
self._loop.call_soon(futures._set_result_unless_cancelled,
|
| 490 |
+
waiter, None)
|
| 491 |
+
|
| 492 |
+
def _add_reader(self, fd, callback):
|
| 493 |
+
if not self.is_reading():
|
| 494 |
+
return
|
| 495 |
+
self._loop._add_reader(fd, callback)
|
| 496 |
+
|
| 497 |
+
def is_reading(self):
|
| 498 |
+
return not self._paused and not self._closing
|
| 499 |
+
|
| 500 |
+
def __repr__(self):
|
| 501 |
+
info = [self.__class__.__name__]
|
| 502 |
+
if self._pipe is None:
|
| 503 |
+
info.append('closed')
|
| 504 |
+
elif self._closing:
|
| 505 |
+
info.append('closing')
|
| 506 |
+
info.append(f'fd={self._fileno}')
|
| 507 |
+
selector = getattr(self._loop, '_selector', None)
|
| 508 |
+
if self._pipe is not None and selector is not None:
|
| 509 |
+
polling = selector_events._test_selector_event(
|
| 510 |
+
selector, self._fileno, selectors.EVENT_READ)
|
| 511 |
+
if polling:
|
| 512 |
+
info.append('polling')
|
| 513 |
+
else:
|
| 514 |
+
info.append('idle')
|
| 515 |
+
elif self._pipe is not None:
|
| 516 |
+
info.append('open')
|
| 517 |
+
else:
|
| 518 |
+
info.append('closed')
|
| 519 |
+
return '<{}>'.format(' '.join(info))
|
| 520 |
+
|
| 521 |
+
def _read_ready(self):
|
| 522 |
+
try:
|
| 523 |
+
data = os.read(self._fileno, self.max_size)
|
| 524 |
+
except (BlockingIOError, InterruptedError):
|
| 525 |
+
pass
|
| 526 |
+
except OSError as exc:
|
| 527 |
+
self._fatal_error(exc, 'Fatal read error on pipe transport')
|
| 528 |
+
else:
|
| 529 |
+
if data:
|
| 530 |
+
self._protocol.data_received(data)
|
| 531 |
+
else:
|
| 532 |
+
if self._loop.get_debug():
|
| 533 |
+
logger.info("%r was closed by peer", self)
|
| 534 |
+
self._closing = True
|
| 535 |
+
self._loop._remove_reader(self._fileno)
|
| 536 |
+
self._loop.call_soon(self._protocol.eof_received)
|
| 537 |
+
self._loop.call_soon(self._call_connection_lost, None)
|
| 538 |
+
|
| 539 |
+
def pause_reading(self):
|
| 540 |
+
if not self.is_reading():
|
| 541 |
+
return
|
| 542 |
+
self._paused = True
|
| 543 |
+
self._loop._remove_reader(self._fileno)
|
| 544 |
+
if self._loop.get_debug():
|
| 545 |
+
logger.debug("%r pauses reading", self)
|
| 546 |
+
|
| 547 |
+
def resume_reading(self):
|
| 548 |
+
if self._closing or not self._paused:
|
| 549 |
+
return
|
| 550 |
+
self._paused = False
|
| 551 |
+
self._loop._add_reader(self._fileno, self._read_ready)
|
| 552 |
+
if self._loop.get_debug():
|
| 553 |
+
logger.debug("%r resumes reading", self)
|
| 554 |
+
|
| 555 |
+
def set_protocol(self, protocol):
|
| 556 |
+
self._protocol = protocol
|
| 557 |
+
|
| 558 |
+
def get_protocol(self):
|
| 559 |
+
return self._protocol
|
| 560 |
+
|
| 561 |
+
def is_closing(self):
|
| 562 |
+
return self._closing
|
| 563 |
+
|
| 564 |
+
def close(self):
|
| 565 |
+
if not self._closing:
|
| 566 |
+
self._close(None)
|
| 567 |
+
|
| 568 |
+
def __del__(self, _warn=warnings.warn):
|
| 569 |
+
if self._pipe is not None:
|
| 570 |
+
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
|
| 571 |
+
self._pipe.close()
|
| 572 |
+
|
| 573 |
+
def _fatal_error(self, exc, message='Fatal error on pipe transport'):
|
| 574 |
+
# should be called by exception handler only
|
| 575 |
+
if (isinstance(exc, OSError) and exc.errno == errno.EIO):
|
| 576 |
+
if self._loop.get_debug():
|
| 577 |
+
logger.debug("%r: %s", self, message, exc_info=True)
|
| 578 |
+
else:
|
| 579 |
+
self._loop.call_exception_handler({
|
| 580 |
+
'message': message,
|
| 581 |
+
'exception': exc,
|
| 582 |
+
'transport': self,
|
| 583 |
+
'protocol': self._protocol,
|
| 584 |
+
})
|
| 585 |
+
self._close(exc)
|
| 586 |
+
|
| 587 |
+
def _close(self, exc):
|
| 588 |
+
self._closing = True
|
| 589 |
+
self._loop._remove_reader(self._fileno)
|
| 590 |
+
self._loop.call_soon(self._call_connection_lost, exc)
|
| 591 |
+
|
| 592 |
+
def _call_connection_lost(self, exc):
|
| 593 |
+
try:
|
| 594 |
+
self._protocol.connection_lost(exc)
|
| 595 |
+
finally:
|
| 596 |
+
self._pipe.close()
|
| 597 |
+
self._pipe = None
|
| 598 |
+
self._protocol = None
|
| 599 |
+
self._loop = None
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
class _UnixWritePipeTransport(transports._FlowControlMixin,
|
| 603 |
+
transports.WriteTransport):
|
| 604 |
+
|
| 605 |
+
def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
|
| 606 |
+
super().__init__(extra, loop)
|
| 607 |
+
self._extra['pipe'] = pipe
|
| 608 |
+
self._pipe = pipe
|
| 609 |
+
self._fileno = pipe.fileno()
|
| 610 |
+
self._protocol = protocol
|
| 611 |
+
self._buffer = bytearray()
|
| 612 |
+
self._conn_lost = 0
|
| 613 |
+
self._closing = False # Set when close() or write_eof() called.
|
| 614 |
+
|
| 615 |
+
mode = os.fstat(self._fileno).st_mode
|
| 616 |
+
is_char = stat.S_ISCHR(mode)
|
| 617 |
+
is_fifo = stat.S_ISFIFO(mode)
|
| 618 |
+
is_socket = stat.S_ISSOCK(mode)
|
| 619 |
+
if not (is_char or is_fifo or is_socket):
|
| 620 |
+
self._pipe = None
|
| 621 |
+
self._fileno = None
|
| 622 |
+
self._protocol = None
|
| 623 |
+
raise ValueError("Pipe transport is only for "
|
| 624 |
+
"pipes, sockets and character devices")
|
| 625 |
+
|
| 626 |
+
os.set_blocking(self._fileno, False)
|
| 627 |
+
self._loop.call_soon(self._protocol.connection_made, self)
|
| 628 |
+
|
| 629 |
+
# On AIX, the reader trick (to be notified when the read end of the
|
| 630 |
+
# socket is closed) only works for sockets. On other platforms it
|
| 631 |
+
# works for pipes and sockets. (Exception: OS X 10.4? Issue #19294.)
|
| 632 |
+
if is_socket or (is_fifo and not sys.platform.startswith("aix")):
|
| 633 |
+
# only start reading when connection_made() has been called
|
| 634 |
+
self._loop.call_soon(self._loop._add_reader,
|
| 635 |
+
self._fileno, self._read_ready)
|
| 636 |
+
|
| 637 |
+
if waiter is not None:
|
| 638 |
+
# only wake up the waiter when connection_made() has been called
|
| 639 |
+
self._loop.call_soon(futures._set_result_unless_cancelled,
|
| 640 |
+
waiter, None)
|
| 641 |
+
|
| 642 |
+
def __repr__(self):
|
| 643 |
+
info = [self.__class__.__name__]
|
| 644 |
+
if self._pipe is None:
|
| 645 |
+
info.append('closed')
|
| 646 |
+
elif self._closing:
|
| 647 |
+
info.append('closing')
|
| 648 |
+
info.append(f'fd={self._fileno}')
|
| 649 |
+
selector = getattr(self._loop, '_selector', None)
|
| 650 |
+
if self._pipe is not None and selector is not None:
|
| 651 |
+
polling = selector_events._test_selector_event(
|
| 652 |
+
selector, self._fileno, selectors.EVENT_WRITE)
|
| 653 |
+
if polling:
|
| 654 |
+
info.append('polling')
|
| 655 |
+
else:
|
| 656 |
+
info.append('idle')
|
| 657 |
+
|
| 658 |
+
bufsize = self.get_write_buffer_size()
|
| 659 |
+
info.append(f'bufsize={bufsize}')
|
| 660 |
+
elif self._pipe is not None:
|
| 661 |
+
info.append('open')
|
| 662 |
+
else:
|
| 663 |
+
info.append('closed')
|
| 664 |
+
return '<{}>'.format(' '.join(info))
|
| 665 |
+
|
| 666 |
+
def get_write_buffer_size(self):
|
| 667 |
+
return len(self._buffer)
|
| 668 |
+
|
| 669 |
+
def _read_ready(self):
|
| 670 |
+
# Pipe was closed by peer.
|
| 671 |
+
if self._loop.get_debug():
|
| 672 |
+
logger.info("%r was closed by peer", self)
|
| 673 |
+
if self._buffer:
|
| 674 |
+
self._close(BrokenPipeError())
|
| 675 |
+
else:
|
| 676 |
+
self._close()
|
| 677 |
+
|
| 678 |
+
def write(self, data):
|
| 679 |
+
assert isinstance(data, (bytes, bytearray, memoryview)), repr(data)
|
| 680 |
+
if isinstance(data, bytearray):
|
| 681 |
+
data = memoryview(data)
|
| 682 |
+
if not data:
|
| 683 |
+
return
|
| 684 |
+
|
| 685 |
+
if self._conn_lost or self._closing:
|
| 686 |
+
if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
|
| 687 |
+
logger.warning('pipe closed by peer or '
|
| 688 |
+
'os.write(pipe, data) raised exception.')
|
| 689 |
+
self._conn_lost += 1
|
| 690 |
+
return
|
| 691 |
+
|
| 692 |
+
if not self._buffer:
|
| 693 |
+
# Attempt to send it right away first.
|
| 694 |
+
try:
|
| 695 |
+
n = os.write(self._fileno, data)
|
| 696 |
+
except (BlockingIOError, InterruptedError):
|
| 697 |
+
n = 0
|
| 698 |
+
except (SystemExit, KeyboardInterrupt):
|
| 699 |
+
raise
|
| 700 |
+
except BaseException as exc:
|
| 701 |
+
self._conn_lost += 1
|
| 702 |
+
self._fatal_error(exc, 'Fatal write error on pipe transport')
|
| 703 |
+
return
|
| 704 |
+
if n == len(data):
|
| 705 |
+
return
|
| 706 |
+
elif n > 0:
|
| 707 |
+
data = memoryview(data)[n:]
|
| 708 |
+
self._loop._add_writer(self._fileno, self._write_ready)
|
| 709 |
+
|
| 710 |
+
self._buffer += data
|
| 711 |
+
self._maybe_pause_protocol()
|
| 712 |
+
|
| 713 |
+
def _write_ready(self):
|
| 714 |
+
assert self._buffer, 'Data should not be empty'
|
| 715 |
+
|
| 716 |
+
try:
|
| 717 |
+
n = os.write(self._fileno, self._buffer)
|
| 718 |
+
except (BlockingIOError, InterruptedError):
|
| 719 |
+
pass
|
| 720 |
+
except (SystemExit, KeyboardInterrupt):
|
| 721 |
+
raise
|
| 722 |
+
except BaseException as exc:
|
| 723 |
+
self._buffer.clear()
|
| 724 |
+
self._conn_lost += 1
|
| 725 |
+
# Remove writer here, _fatal_error() doesn't it
|
| 726 |
+
# because _buffer is empty.
|
| 727 |
+
self._loop._remove_writer(self._fileno)
|
| 728 |
+
self._fatal_error(exc, 'Fatal write error on pipe transport')
|
| 729 |
+
else:
|
| 730 |
+
if n == len(self._buffer):
|
| 731 |
+
self._buffer.clear()
|
| 732 |
+
self._loop._remove_writer(self._fileno)
|
| 733 |
+
self._maybe_resume_protocol() # May append to buffer.
|
| 734 |
+
if self._closing:
|
| 735 |
+
self._loop._remove_reader(self._fileno)
|
| 736 |
+
self._call_connection_lost(None)
|
| 737 |
+
return
|
| 738 |
+
elif n > 0:
|
| 739 |
+
del self._buffer[:n]
|
| 740 |
+
|
| 741 |
+
def can_write_eof(self):
|
| 742 |
+
return True
|
| 743 |
+
|
| 744 |
+
def write_eof(self):
|
| 745 |
+
if self._closing:
|
| 746 |
+
return
|
| 747 |
+
assert self._pipe
|
| 748 |
+
self._closing = True
|
| 749 |
+
if not self._buffer:
|
| 750 |
+
self._loop._remove_reader(self._fileno)
|
| 751 |
+
self._loop.call_soon(self._call_connection_lost, None)
|
| 752 |
+
|
| 753 |
+
def set_protocol(self, protocol):
|
| 754 |
+
self._protocol = protocol
|
| 755 |
+
|
| 756 |
+
def get_protocol(self):
|
| 757 |
+
return self._protocol
|
| 758 |
+
|
| 759 |
+
def is_closing(self):
|
| 760 |
+
return self._closing
|
| 761 |
+
|
| 762 |
+
def close(self):
|
| 763 |
+
if self._pipe is not None and not self._closing:
|
| 764 |
+
# write_eof is all what we needed to close the write pipe
|
| 765 |
+
self.write_eof()
|
| 766 |
+
|
| 767 |
+
def __del__(self, _warn=warnings.warn):
|
| 768 |
+
if self._pipe is not None:
|
| 769 |
+
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
|
| 770 |
+
self._pipe.close()
|
| 771 |
+
|
| 772 |
+
def abort(self):
|
| 773 |
+
self._close(None)
|
| 774 |
+
|
| 775 |
+
def _fatal_error(self, exc, message='Fatal error on pipe transport'):
|
| 776 |
+
# should be called by exception handler only
|
| 777 |
+
if isinstance(exc, OSError):
|
| 778 |
+
if self._loop.get_debug():
|
| 779 |
+
logger.debug("%r: %s", self, message, exc_info=True)
|
| 780 |
+
else:
|
| 781 |
+
self._loop.call_exception_handler({
|
| 782 |
+
'message': message,
|
| 783 |
+
'exception': exc,
|
| 784 |
+
'transport': self,
|
| 785 |
+
'protocol': self._protocol,
|
| 786 |
+
})
|
| 787 |
+
self._close(exc)
|
| 788 |
+
|
| 789 |
+
def _close(self, exc=None):
|
| 790 |
+
self._closing = True
|
| 791 |
+
if self._buffer:
|
| 792 |
+
self._loop._remove_writer(self._fileno)
|
| 793 |
+
self._buffer.clear()
|
| 794 |
+
self._loop._remove_reader(self._fileno)
|
| 795 |
+
self._loop.call_soon(self._call_connection_lost, exc)
|
| 796 |
+
|
| 797 |
+
def _call_connection_lost(self, exc):
|
| 798 |
+
try:
|
| 799 |
+
self._protocol.connection_lost(exc)
|
| 800 |
+
finally:
|
| 801 |
+
self._pipe.close()
|
| 802 |
+
self._pipe = None
|
| 803 |
+
self._protocol = None
|
| 804 |
+
self._loop = None
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
class _UnixSubprocessTransport(base_subprocess.BaseSubprocessTransport):
|
| 808 |
+
|
| 809 |
+
def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
|
| 810 |
+
stdin_w = None
|
| 811 |
+
if stdin == subprocess.PIPE and sys.platform.startswith('aix'):
|
| 812 |
+
# Use a socket pair for stdin on AIX, since it does not
|
| 813 |
+
# support selecting read events on the write end of a
|
| 814 |
+
# socket (which we use in order to detect closing of the
|
| 815 |
+
# other end).
|
| 816 |
+
stdin, stdin_w = socket.socketpair()
|
| 817 |
+
try:
|
| 818 |
+
self._proc = subprocess.Popen(
|
| 819 |
+
args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
|
| 820 |
+
universal_newlines=False, bufsize=bufsize, **kwargs)
|
| 821 |
+
if stdin_w is not None:
|
| 822 |
+
stdin.close()
|
| 823 |
+
self._proc.stdin = open(stdin_w.detach(), 'wb', buffering=bufsize)
|
| 824 |
+
stdin_w = None
|
| 825 |
+
finally:
|
| 826 |
+
if stdin_w is not None:
|
| 827 |
+
stdin.close()
|
| 828 |
+
stdin_w.close()
|
| 829 |
+
|
| 830 |
+
|
| 831 |
+
class AbstractChildWatcher:
|
| 832 |
+
"""Abstract base class for monitoring child processes.
|
| 833 |
+
|
| 834 |
+
Objects derived from this class monitor a collection of subprocesses and
|
| 835 |
+
report their termination or interruption by a signal.
|
| 836 |
+
|
| 837 |
+
New callbacks are registered with .add_child_handler(). Starting a new
|
| 838 |
+
process must be done within a 'with' block to allow the watcher to suspend
|
| 839 |
+
its activity until the new process if fully registered (this is needed to
|
| 840 |
+
prevent a race condition in some implementations).
|
| 841 |
+
|
| 842 |
+
Example:
|
| 843 |
+
with watcher:
|
| 844 |
+
proc = subprocess.Popen("sleep 1")
|
| 845 |
+
watcher.add_child_handler(proc.pid, callback)
|
| 846 |
+
|
| 847 |
+
Notes:
|
| 848 |
+
Implementations of this class must be thread-safe.
|
| 849 |
+
|
| 850 |
+
Since child watcher objects may catch the SIGCHLD signal and call
|
| 851 |
+
waitpid(-1), there should be only one active object per process.
|
| 852 |
+
"""
|
| 853 |
+
|
| 854 |
+
def add_child_handler(self, pid, callback, *args):
|
| 855 |
+
"""Register a new child handler.
|
| 856 |
+
|
| 857 |
+
Arrange for callback(pid, returncode, *args) to be called when
|
| 858 |
+
process 'pid' terminates. Specifying another callback for the same
|
| 859 |
+
process replaces the previous handler.
|
| 860 |
+
|
| 861 |
+
Note: callback() must be thread-safe.
|
| 862 |
+
"""
|
| 863 |
+
raise NotImplementedError()
|
| 864 |
+
|
| 865 |
+
def remove_child_handler(self, pid):
|
| 866 |
+
"""Removes the handler for process 'pid'.
|
| 867 |
+
|
| 868 |
+
The function returns True if the handler was successfully removed,
|
| 869 |
+
False if there was nothing to remove."""
|
| 870 |
+
|
| 871 |
+
raise NotImplementedError()
|
| 872 |
+
|
| 873 |
+
def attach_loop(self, loop):
|
| 874 |
+
"""Attach the watcher to an event loop.
|
| 875 |
+
|
| 876 |
+
If the watcher was previously attached to an event loop, then it is
|
| 877 |
+
first detached before attaching to the new loop.
|
| 878 |
+
|
| 879 |
+
Note: loop may be None.
|
| 880 |
+
"""
|
| 881 |
+
raise NotImplementedError()
|
| 882 |
+
|
| 883 |
+
def close(self):
|
| 884 |
+
"""Close the watcher.
|
| 885 |
+
|
| 886 |
+
This must be called to make sure that any underlying resource is freed.
|
| 887 |
+
"""
|
| 888 |
+
raise NotImplementedError()
|
| 889 |
+
|
| 890 |
+
def is_active(self):
|
| 891 |
+
"""Return ``True`` if the watcher is active and is used by the event loop.
|
| 892 |
+
|
| 893 |
+
Return True if the watcher is installed and ready to handle process exit
|
| 894 |
+
notifications.
|
| 895 |
+
|
| 896 |
+
"""
|
| 897 |
+
raise NotImplementedError()
|
| 898 |
+
|
| 899 |
+
def __enter__(self):
|
| 900 |
+
"""Enter the watcher's context and allow starting new processes
|
| 901 |
+
|
| 902 |
+
This function must return self"""
|
| 903 |
+
raise NotImplementedError()
|
| 904 |
+
|
| 905 |
+
def __exit__(self, a, b, c):
|
| 906 |
+
"""Exit the watcher's context"""
|
| 907 |
+
raise NotImplementedError()
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
class PidfdChildWatcher(AbstractChildWatcher):
|
| 911 |
+
"""Child watcher implementation using Linux's pid file descriptors.
|
| 912 |
+
|
| 913 |
+
This child watcher polls process file descriptors (pidfds) to await child
|
| 914 |
+
process termination. In some respects, PidfdChildWatcher is a "Goldilocks"
|
| 915 |
+
child watcher implementation. It doesn't require signals or threads, doesn't
|
| 916 |
+
interfere with any processes launched outside the event loop, and scales
|
| 917 |
+
linearly with the number of subprocesses launched by the event loop. The
|
| 918 |
+
main disadvantage is that pidfds are specific to Linux, and only work on
|
| 919 |
+
recent (5.3+) kernels.
|
| 920 |
+
"""
|
| 921 |
+
|
| 922 |
+
def __init__(self):
|
| 923 |
+
self._loop = None
|
| 924 |
+
self._callbacks = {}
|
| 925 |
+
|
| 926 |
+
def __enter__(self):
|
| 927 |
+
return self
|
| 928 |
+
|
| 929 |
+
def __exit__(self, exc_type, exc_value, exc_traceback):
|
| 930 |
+
pass
|
| 931 |
+
|
| 932 |
+
def is_active(self):
|
| 933 |
+
return self._loop is not None and self._loop.is_running()
|
| 934 |
+
|
| 935 |
+
def close(self):
|
| 936 |
+
self.attach_loop(None)
|
| 937 |
+
|
| 938 |
+
def attach_loop(self, loop):
|
| 939 |
+
if self._loop is not None and loop is None and self._callbacks:
|
| 940 |
+
warnings.warn(
|
| 941 |
+
'A loop is being detached '
|
| 942 |
+
'from a child watcher with pending handlers',
|
| 943 |
+
RuntimeWarning)
|
| 944 |
+
for pidfd, _, _ in self._callbacks.values():
|
| 945 |
+
self._loop._remove_reader(pidfd)
|
| 946 |
+
os.close(pidfd)
|
| 947 |
+
self._callbacks.clear()
|
| 948 |
+
self._loop = loop
|
| 949 |
+
|
| 950 |
+
def add_child_handler(self, pid, callback, *args):
|
| 951 |
+
existing = self._callbacks.get(pid)
|
| 952 |
+
if existing is not None:
|
| 953 |
+
self._callbacks[pid] = existing[0], callback, args
|
| 954 |
+
else:
|
| 955 |
+
pidfd = os.pidfd_open(pid)
|
| 956 |
+
self._loop._add_reader(pidfd, self._do_wait, pid)
|
| 957 |
+
self._callbacks[pid] = pidfd, callback, args
|
| 958 |
+
|
| 959 |
+
def _do_wait(self, pid):
|
| 960 |
+
pidfd, callback, args = self._callbacks.pop(pid)
|
| 961 |
+
self._loop._remove_reader(pidfd)
|
| 962 |
+
try:
|
| 963 |
+
_, status = os.waitpid(pid, 0)
|
| 964 |
+
except ChildProcessError:
|
| 965 |
+
# The child process is already reaped
|
| 966 |
+
# (may happen if waitpid() is called elsewhere).
|
| 967 |
+
returncode = 255
|
| 968 |
+
logger.warning(
|
| 969 |
+
"child process pid %d exit status already read: "
|
| 970 |
+
" will report returncode 255",
|
| 971 |
+
pid)
|
| 972 |
+
else:
|
| 973 |
+
returncode = waitstatus_to_exitcode(status)
|
| 974 |
+
|
| 975 |
+
os.close(pidfd)
|
| 976 |
+
callback(pid, returncode, *args)
|
| 977 |
+
|
| 978 |
+
def remove_child_handler(self, pid):
|
| 979 |
+
try:
|
| 980 |
+
pidfd, _, _ = self._callbacks.pop(pid)
|
| 981 |
+
except KeyError:
|
| 982 |
+
return False
|
| 983 |
+
self._loop._remove_reader(pidfd)
|
| 984 |
+
os.close(pidfd)
|
| 985 |
+
return True
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
class BaseChildWatcher(AbstractChildWatcher):
|
| 989 |
+
|
| 990 |
+
def __init__(self):
|
| 991 |
+
self._loop = None
|
| 992 |
+
self._callbacks = {}
|
| 993 |
+
|
| 994 |
+
def close(self):
|
| 995 |
+
self.attach_loop(None)
|
| 996 |
+
|
| 997 |
+
def is_active(self):
|
| 998 |
+
return self._loop is not None and self._loop.is_running()
|
| 999 |
+
|
| 1000 |
+
def _do_waitpid(self, expected_pid):
|
| 1001 |
+
raise NotImplementedError()
|
| 1002 |
+
|
| 1003 |
+
def _do_waitpid_all(self):
|
| 1004 |
+
raise NotImplementedError()
|
| 1005 |
+
|
| 1006 |
+
def attach_loop(self, loop):
|
| 1007 |
+
assert loop is None or isinstance(loop, events.AbstractEventLoop)
|
| 1008 |
+
|
| 1009 |
+
if self._loop is not None and loop is None and self._callbacks:
|
| 1010 |
+
warnings.warn(
|
| 1011 |
+
'A loop is being detached '
|
| 1012 |
+
'from a child watcher with pending handlers',
|
| 1013 |
+
RuntimeWarning)
|
| 1014 |
+
|
| 1015 |
+
if self._loop is not None:
|
| 1016 |
+
self._loop.remove_signal_handler(signal.SIGCHLD)
|
| 1017 |
+
|
| 1018 |
+
self._loop = loop
|
| 1019 |
+
if loop is not None:
|
| 1020 |
+
loop.add_signal_handler(signal.SIGCHLD, self._sig_chld)
|
| 1021 |
+
|
| 1022 |
+
# Prevent a race condition in case a child terminated
|
| 1023 |
+
# during the switch.
|
| 1024 |
+
self._do_waitpid_all()
|
| 1025 |
+
|
| 1026 |
+
def _sig_chld(self):
|
| 1027 |
+
try:
|
| 1028 |
+
self._do_waitpid_all()
|
| 1029 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1030 |
+
raise
|
| 1031 |
+
except BaseException as exc:
|
| 1032 |
+
# self._loop should always be available here
|
| 1033 |
+
# as '_sig_chld' is added as a signal handler
|
| 1034 |
+
# in 'attach_loop'
|
| 1035 |
+
self._loop.call_exception_handler({
|
| 1036 |
+
'message': 'Unknown exception in SIGCHLD handler',
|
| 1037 |
+
'exception': exc,
|
| 1038 |
+
})
|
| 1039 |
+
|
| 1040 |
+
|
| 1041 |
+
class SafeChildWatcher(BaseChildWatcher):
|
| 1042 |
+
"""'Safe' child watcher implementation.
|
| 1043 |
+
|
| 1044 |
+
This implementation avoids disrupting other code spawning processes by
|
| 1045 |
+
polling explicitly each process in the SIGCHLD handler instead of calling
|
| 1046 |
+
os.waitpid(-1).
|
| 1047 |
+
|
| 1048 |
+
This is a safe solution but it has a significant overhead when handling a
|
| 1049 |
+
big number of children (O(n) each time SIGCHLD is raised)
|
| 1050 |
+
"""
|
| 1051 |
+
|
| 1052 |
+
def close(self):
|
| 1053 |
+
self._callbacks.clear()
|
| 1054 |
+
super().close()
|
| 1055 |
+
|
| 1056 |
+
def __enter__(self):
|
| 1057 |
+
return self
|
| 1058 |
+
|
| 1059 |
+
def __exit__(self, a, b, c):
|
| 1060 |
+
pass
|
| 1061 |
+
|
| 1062 |
+
def add_child_handler(self, pid, callback, *args):
|
| 1063 |
+
self._callbacks[pid] = (callback, args)
|
| 1064 |
+
|
| 1065 |
+
# Prevent a race condition in case the child is already terminated.
|
| 1066 |
+
self._do_waitpid(pid)
|
| 1067 |
+
|
| 1068 |
+
def remove_child_handler(self, pid):
|
| 1069 |
+
try:
|
| 1070 |
+
del self._callbacks[pid]
|
| 1071 |
+
return True
|
| 1072 |
+
except KeyError:
|
| 1073 |
+
return False
|
| 1074 |
+
|
| 1075 |
+
def _do_waitpid_all(self):
|
| 1076 |
+
|
| 1077 |
+
for pid in list(self._callbacks):
|
| 1078 |
+
self._do_waitpid(pid)
|
| 1079 |
+
|
| 1080 |
+
def _do_waitpid(self, expected_pid):
|
| 1081 |
+
assert expected_pid > 0
|
| 1082 |
+
|
| 1083 |
+
try:
|
| 1084 |
+
pid, status = os.waitpid(expected_pid, os.WNOHANG)
|
| 1085 |
+
except ChildProcessError:
|
| 1086 |
+
# The child process is already reaped
|
| 1087 |
+
# (may happen if waitpid() is called elsewhere).
|
| 1088 |
+
pid = expected_pid
|
| 1089 |
+
returncode = 255
|
| 1090 |
+
logger.warning(
|
| 1091 |
+
"Unknown child process pid %d, will report returncode 255",
|
| 1092 |
+
pid)
|
| 1093 |
+
else:
|
| 1094 |
+
if pid == 0:
|
| 1095 |
+
# The child process is still alive.
|
| 1096 |
+
return
|
| 1097 |
+
|
| 1098 |
+
returncode = waitstatus_to_exitcode(status)
|
| 1099 |
+
if self._loop.get_debug():
|
| 1100 |
+
logger.debug('process %s exited with returncode %s',
|
| 1101 |
+
expected_pid, returncode)
|
| 1102 |
+
|
| 1103 |
+
try:
|
| 1104 |
+
callback, args = self._callbacks.pop(pid)
|
| 1105 |
+
except KeyError: # pragma: no cover
|
| 1106 |
+
# May happen if .remove_child_handler() is called
|
| 1107 |
+
# after os.waitpid() returns.
|
| 1108 |
+
if self._loop.get_debug():
|
| 1109 |
+
logger.warning("Child watcher got an unexpected pid: %r",
|
| 1110 |
+
pid, exc_info=True)
|
| 1111 |
+
else:
|
| 1112 |
+
callback(pid, returncode, *args)
|
| 1113 |
+
|
| 1114 |
+
|
| 1115 |
+
class FastChildWatcher(BaseChildWatcher):
|
| 1116 |
+
"""'Fast' child watcher implementation.
|
| 1117 |
+
|
| 1118 |
+
This implementation reaps every terminated processes by calling
|
| 1119 |
+
os.waitpid(-1) directly, possibly breaking other code spawning processes
|
| 1120 |
+
and waiting for their termination.
|
| 1121 |
+
|
| 1122 |
+
There is no noticeable overhead when handling a big number of children
|
| 1123 |
+
(O(1) each time a child terminates).
|
| 1124 |
+
"""
|
| 1125 |
+
def __init__(self):
|
| 1126 |
+
super().__init__()
|
| 1127 |
+
self._lock = threading.Lock()
|
| 1128 |
+
self._zombies = {}
|
| 1129 |
+
self._forks = 0
|
| 1130 |
+
|
| 1131 |
+
def close(self):
|
| 1132 |
+
self._callbacks.clear()
|
| 1133 |
+
self._zombies.clear()
|
| 1134 |
+
super().close()
|
| 1135 |
+
|
| 1136 |
+
def __enter__(self):
|
| 1137 |
+
with self._lock:
|
| 1138 |
+
self._forks += 1
|
| 1139 |
+
|
| 1140 |
+
return self
|
| 1141 |
+
|
| 1142 |
+
def __exit__(self, a, b, c):
|
| 1143 |
+
with self._lock:
|
| 1144 |
+
self._forks -= 1
|
| 1145 |
+
|
| 1146 |
+
if self._forks or not self._zombies:
|
| 1147 |
+
return
|
| 1148 |
+
|
| 1149 |
+
collateral_victims = str(self._zombies)
|
| 1150 |
+
self._zombies.clear()
|
| 1151 |
+
|
| 1152 |
+
logger.warning(
|
| 1153 |
+
"Caught subprocesses termination from unknown pids: %s",
|
| 1154 |
+
collateral_victims)
|
| 1155 |
+
|
| 1156 |
+
def add_child_handler(self, pid, callback, *args):
|
| 1157 |
+
assert self._forks, "Must use the context manager"
|
| 1158 |
+
|
| 1159 |
+
with self._lock:
|
| 1160 |
+
try:
|
| 1161 |
+
returncode = self._zombies.pop(pid)
|
| 1162 |
+
except KeyError:
|
| 1163 |
+
# The child is running.
|
| 1164 |
+
self._callbacks[pid] = callback, args
|
| 1165 |
+
return
|
| 1166 |
+
|
| 1167 |
+
# The child is dead already. We can fire the callback.
|
| 1168 |
+
callback(pid, returncode, *args)
|
| 1169 |
+
|
| 1170 |
+
def remove_child_handler(self, pid):
|
| 1171 |
+
try:
|
| 1172 |
+
del self._callbacks[pid]
|
| 1173 |
+
return True
|
| 1174 |
+
except KeyError:
|
| 1175 |
+
return False
|
| 1176 |
+
|
| 1177 |
+
def _do_waitpid_all(self):
|
| 1178 |
+
# Because of signal coalescing, we must keep calling waitpid() as
|
| 1179 |
+
# long as we're able to reap a child.
|
| 1180 |
+
while True:
|
| 1181 |
+
try:
|
| 1182 |
+
pid, status = os.waitpid(-1, os.WNOHANG)
|
| 1183 |
+
except ChildProcessError:
|
| 1184 |
+
# No more child processes exist.
|
| 1185 |
+
return
|
| 1186 |
+
else:
|
| 1187 |
+
if pid == 0:
|
| 1188 |
+
# A child process is still alive.
|
| 1189 |
+
return
|
| 1190 |
+
|
| 1191 |
+
returncode = waitstatus_to_exitcode(status)
|
| 1192 |
+
|
| 1193 |
+
with self._lock:
|
| 1194 |
+
try:
|
| 1195 |
+
callback, args = self._callbacks.pop(pid)
|
| 1196 |
+
except KeyError:
|
| 1197 |
+
# unknown child
|
| 1198 |
+
if self._forks:
|
| 1199 |
+
# It may not be registered yet.
|
| 1200 |
+
self._zombies[pid] = returncode
|
| 1201 |
+
if self._loop.get_debug():
|
| 1202 |
+
logger.debug('unknown process %s exited '
|
| 1203 |
+
'with returncode %s',
|
| 1204 |
+
pid, returncode)
|
| 1205 |
+
continue
|
| 1206 |
+
callback = None
|
| 1207 |
+
else:
|
| 1208 |
+
if self._loop.get_debug():
|
| 1209 |
+
logger.debug('process %s exited with returncode %s',
|
| 1210 |
+
pid, returncode)
|
| 1211 |
+
|
| 1212 |
+
if callback is None:
|
| 1213 |
+
logger.warning(
|
| 1214 |
+
"Caught subprocess termination from unknown pid: "
|
| 1215 |
+
"%d -> %d", pid, returncode)
|
| 1216 |
+
else:
|
| 1217 |
+
callback(pid, returncode, *args)
|
| 1218 |
+
|
| 1219 |
+
|
| 1220 |
+
class MultiLoopChildWatcher(AbstractChildWatcher):
|
| 1221 |
+
"""A watcher that doesn't require running loop in the main thread.
|
| 1222 |
+
|
| 1223 |
+
This implementation registers a SIGCHLD signal handler on
|
| 1224 |
+
instantiation (which may conflict with other code that
|
| 1225 |
+
install own handler for this signal).
|
| 1226 |
+
|
| 1227 |
+
The solution is safe but it has a significant overhead when
|
| 1228 |
+
handling a big number of processes (*O(n)* each time a
|
| 1229 |
+
SIGCHLD is received).
|
| 1230 |
+
"""
|
| 1231 |
+
|
| 1232 |
+
# Implementation note:
|
| 1233 |
+
# The class keeps compatibility with AbstractChildWatcher ABC
|
| 1234 |
+
# To achieve this it has empty attach_loop() method
|
| 1235 |
+
# and doesn't accept explicit loop argument
|
| 1236 |
+
# for add_child_handler()/remove_child_handler()
|
| 1237 |
+
# but retrieves the current loop by get_running_loop()
|
| 1238 |
+
|
| 1239 |
+
def __init__(self):
|
| 1240 |
+
self._callbacks = {}
|
| 1241 |
+
self._saved_sighandler = None
|
| 1242 |
+
|
| 1243 |
+
def is_active(self):
|
| 1244 |
+
return self._saved_sighandler is not None
|
| 1245 |
+
|
| 1246 |
+
def close(self):
|
| 1247 |
+
self._callbacks.clear()
|
| 1248 |
+
if self._saved_sighandler is None:
|
| 1249 |
+
return
|
| 1250 |
+
|
| 1251 |
+
handler = signal.getsignal(signal.SIGCHLD)
|
| 1252 |
+
if handler != self._sig_chld:
|
| 1253 |
+
logger.warning("SIGCHLD handler was changed by outside code")
|
| 1254 |
+
else:
|
| 1255 |
+
signal.signal(signal.SIGCHLD, self._saved_sighandler)
|
| 1256 |
+
self._saved_sighandler = None
|
| 1257 |
+
|
| 1258 |
+
def __enter__(self):
|
| 1259 |
+
return self
|
| 1260 |
+
|
| 1261 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 1262 |
+
pass
|
| 1263 |
+
|
| 1264 |
+
def add_child_handler(self, pid, callback, *args):
|
| 1265 |
+
loop = events.get_running_loop()
|
| 1266 |
+
self._callbacks[pid] = (loop, callback, args)
|
| 1267 |
+
|
| 1268 |
+
# Prevent a race condition in case the child is already terminated.
|
| 1269 |
+
self._do_waitpid(pid)
|
| 1270 |
+
|
| 1271 |
+
def remove_child_handler(self, pid):
|
| 1272 |
+
try:
|
| 1273 |
+
del self._callbacks[pid]
|
| 1274 |
+
return True
|
| 1275 |
+
except KeyError:
|
| 1276 |
+
return False
|
| 1277 |
+
|
| 1278 |
+
def attach_loop(self, loop):
|
| 1279 |
+
# Don't save the loop but initialize itself if called first time
|
| 1280 |
+
# The reason to do it here is that attach_loop() is called from
|
| 1281 |
+
# unix policy only for the main thread.
|
| 1282 |
+
# Main thread is required for subscription on SIGCHLD signal
|
| 1283 |
+
if self._saved_sighandler is not None:
|
| 1284 |
+
return
|
| 1285 |
+
|
| 1286 |
+
self._saved_sighandler = signal.signal(signal.SIGCHLD, self._sig_chld)
|
| 1287 |
+
if self._saved_sighandler is None:
|
| 1288 |
+
logger.warning("Previous SIGCHLD handler was set by non-Python code, "
|
| 1289 |
+
"restore to default handler on watcher close.")
|
| 1290 |
+
self._saved_sighandler = signal.SIG_DFL
|
| 1291 |
+
|
| 1292 |
+
# Set SA_RESTART to limit EINTR occurrences.
|
| 1293 |
+
signal.siginterrupt(signal.SIGCHLD, False)
|
| 1294 |
+
|
| 1295 |
+
def _do_waitpid_all(self):
|
| 1296 |
+
for pid in list(self._callbacks):
|
| 1297 |
+
self._do_waitpid(pid)
|
| 1298 |
+
|
| 1299 |
+
def _do_waitpid(self, expected_pid):
|
| 1300 |
+
assert expected_pid > 0
|
| 1301 |
+
|
| 1302 |
+
try:
|
| 1303 |
+
pid, status = os.waitpid(expected_pid, os.WNOHANG)
|
| 1304 |
+
except ChildProcessError:
|
| 1305 |
+
# The child process is already reaped
|
| 1306 |
+
# (may happen if waitpid() is called elsewhere).
|
| 1307 |
+
pid = expected_pid
|
| 1308 |
+
returncode = 255
|
| 1309 |
+
logger.warning(
|
| 1310 |
+
"Unknown child process pid %d, will report returncode 255",
|
| 1311 |
+
pid)
|
| 1312 |
+
debug_log = False
|
| 1313 |
+
else:
|
| 1314 |
+
if pid == 0:
|
| 1315 |
+
# The child process is still alive.
|
| 1316 |
+
return
|
| 1317 |
+
|
| 1318 |
+
returncode = waitstatus_to_exitcode(status)
|
| 1319 |
+
debug_log = True
|
| 1320 |
+
try:
|
| 1321 |
+
loop, callback, args = self._callbacks.pop(pid)
|
| 1322 |
+
except KeyError: # pragma: no cover
|
| 1323 |
+
# May happen if .remove_child_handler() is called
|
| 1324 |
+
# after os.waitpid() returns.
|
| 1325 |
+
logger.warning("Child watcher got an unexpected pid: %r",
|
| 1326 |
+
pid, exc_info=True)
|
| 1327 |
+
else:
|
| 1328 |
+
if loop.is_closed():
|
| 1329 |
+
logger.warning("Loop %r that handles pid %r is closed", loop, pid)
|
| 1330 |
+
else:
|
| 1331 |
+
if debug_log and loop.get_debug():
|
| 1332 |
+
logger.debug('process %s exited with returncode %s',
|
| 1333 |
+
expected_pid, returncode)
|
| 1334 |
+
loop.call_soon_threadsafe(callback, pid, returncode, *args)
|
| 1335 |
+
|
| 1336 |
+
def _sig_chld(self, signum, frame):
|
| 1337 |
+
try:
|
| 1338 |
+
self._do_waitpid_all()
|
| 1339 |
+
except (SystemExit, KeyboardInterrupt):
|
| 1340 |
+
raise
|
| 1341 |
+
except BaseException:
|
| 1342 |
+
logger.warning('Unknown exception in SIGCHLD handler', exc_info=True)
|
| 1343 |
+
|
| 1344 |
+
|
| 1345 |
+
class ThreadedChildWatcher(AbstractChildWatcher):
|
| 1346 |
+
"""Threaded child watcher implementation.
|
| 1347 |
+
|
| 1348 |
+
The watcher uses a thread per process
|
| 1349 |
+
for waiting for the process finish.
|
| 1350 |
+
|
| 1351 |
+
It doesn't require subscription on POSIX signal
|
| 1352 |
+
but a thread creation is not free.
|
| 1353 |
+
|
| 1354 |
+
The watcher has O(1) complexity, its performance doesn't depend
|
| 1355 |
+
on amount of spawn processes.
|
| 1356 |
+
"""
|
| 1357 |
+
|
| 1358 |
+
def __init__(self):
|
| 1359 |
+
self._pid_counter = itertools.count(0)
|
| 1360 |
+
self._threads = {}
|
| 1361 |
+
|
| 1362 |
+
def is_active(self):
|
| 1363 |
+
return True
|
| 1364 |
+
|
| 1365 |
+
def close(self):
|
| 1366 |
+
pass
|
| 1367 |
+
|
| 1368 |
+
def __enter__(self):
|
| 1369 |
+
return self
|
| 1370 |
+
|
| 1371 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 1372 |
+
pass
|
| 1373 |
+
|
| 1374 |
+
def __del__(self, _warn=warnings.warn):
|
| 1375 |
+
threads = [thread for thread in list(self._threads.values())
|
| 1376 |
+
if thread.is_alive()]
|
| 1377 |
+
if threads:
|
| 1378 |
+
_warn(f"{self.__class__} has registered but not finished child processes",
|
| 1379 |
+
ResourceWarning,
|
| 1380 |
+
source=self)
|
| 1381 |
+
|
| 1382 |
+
def add_child_handler(self, pid, callback, *args):
|
| 1383 |
+
loop = events.get_running_loop()
|
| 1384 |
+
thread = threading.Thread(target=self._do_waitpid,
|
| 1385 |
+
name=f"asyncio-waitpid-{next(self._pid_counter)}",
|
| 1386 |
+
args=(loop, pid, callback, args),
|
| 1387 |
+
daemon=True)
|
| 1388 |
+
self._threads[pid] = thread
|
| 1389 |
+
thread.start()
|
| 1390 |
+
|
| 1391 |
+
def remove_child_handler(self, pid):
|
| 1392 |
+
# asyncio never calls remove_child_handler() !!!
|
| 1393 |
+
# The method is no-op but is implemented because
|
| 1394 |
+
# abstract base classes require it.
|
| 1395 |
+
return True
|
| 1396 |
+
|
| 1397 |
+
def attach_loop(self, loop):
|
| 1398 |
+
pass
|
| 1399 |
+
|
| 1400 |
+
def _do_waitpid(self, loop, expected_pid, callback, args):
|
| 1401 |
+
assert expected_pid > 0
|
| 1402 |
+
|
| 1403 |
+
try:
|
| 1404 |
+
pid, status = os.waitpid(expected_pid, 0)
|
| 1405 |
+
except ChildProcessError:
|
| 1406 |
+
# The child process is already reaped
|
| 1407 |
+
# (may happen if waitpid() is called elsewhere).
|
| 1408 |
+
pid = expected_pid
|
| 1409 |
+
returncode = 255
|
| 1410 |
+
logger.warning(
|
| 1411 |
+
"Unknown child process pid %d, will report returncode 255",
|
| 1412 |
+
pid)
|
| 1413 |
+
else:
|
| 1414 |
+
returncode = waitstatus_to_exitcode(status)
|
| 1415 |
+
if loop.get_debug():
|
| 1416 |
+
logger.debug('process %s exited with returncode %s',
|
| 1417 |
+
expected_pid, returncode)
|
| 1418 |
+
|
| 1419 |
+
if loop.is_closed():
|
| 1420 |
+
logger.warning("Loop %r that handles pid %r is closed", loop, pid)
|
| 1421 |
+
else:
|
| 1422 |
+
loop.call_soon_threadsafe(callback, pid, returncode, *args)
|
| 1423 |
+
|
| 1424 |
+
self._threads.pop(expected_pid)
|
| 1425 |
+
|
| 1426 |
+
|
| 1427 |
+
class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
|
| 1428 |
+
"""UNIX event loop policy with a watcher for child processes."""
|
| 1429 |
+
_loop_factory = _UnixSelectorEventLoop
|
| 1430 |
+
|
| 1431 |
+
def __init__(self):
|
| 1432 |
+
super().__init__()
|
| 1433 |
+
self._watcher = None
|
| 1434 |
+
|
| 1435 |
+
def _init_watcher(self):
|
| 1436 |
+
with events._lock:
|
| 1437 |
+
if self._watcher is None: # pragma: no branch
|
| 1438 |
+
self._watcher = ThreadedChildWatcher()
|
| 1439 |
+
|
| 1440 |
+
def set_event_loop(self, loop):
|
| 1441 |
+
"""Set the event loop.
|
| 1442 |
+
|
| 1443 |
+
As a side effect, if a child watcher was set before, then calling
|
| 1444 |
+
.set_event_loop() from the main thread will call .attach_loop(loop) on
|
| 1445 |
+
the child watcher.
|
| 1446 |
+
"""
|
| 1447 |
+
|
| 1448 |
+
super().set_event_loop(loop)
|
| 1449 |
+
|
| 1450 |
+
if (self._watcher is not None and
|
| 1451 |
+
threading.current_thread() is threading.main_thread()):
|
| 1452 |
+
self._watcher.attach_loop(loop)
|
| 1453 |
+
|
| 1454 |
+
def get_child_watcher(self):
|
| 1455 |
+
"""Get the watcher for child processes.
|
| 1456 |
+
|
| 1457 |
+
If not yet set, a ThreadedChildWatcher object is automatically created.
|
| 1458 |
+
"""
|
| 1459 |
+
if self._watcher is None:
|
| 1460 |
+
self._init_watcher()
|
| 1461 |
+
|
| 1462 |
+
return self._watcher
|
| 1463 |
+
|
| 1464 |
+
def set_child_watcher(self, watcher):
|
| 1465 |
+
"""Set the watcher for child processes."""
|
| 1466 |
+
|
| 1467 |
+
assert watcher is None or isinstance(watcher, AbstractChildWatcher)
|
| 1468 |
+
|
| 1469 |
+
if self._watcher is not None:
|
| 1470 |
+
self._watcher.close()
|
| 1471 |
+
|
| 1472 |
+
self._watcher = watcher
|
| 1473 |
+
|
| 1474 |
+
|
| 1475 |
+
SelectorEventLoop = _UnixSelectorEventLoop
|
| 1476 |
+
DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy
|
micromamba_root/envs/pytorch_env/Lib/asyncio/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Selector and proactor event loops for Windows."""
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
if sys.platform != 'win32': # pragma: no cover
|
| 6 |
+
raise ImportError('win32 only')
|
| 7 |
+
|
| 8 |
+
import _overlapped
|
| 9 |
+
import _winapi
|
| 10 |
+
import errno
|
| 11 |
+
import math
|
| 12 |
+
import msvcrt
|
| 13 |
+
import socket
|
| 14 |
+
import struct
|
| 15 |
+
import time
|
| 16 |
+
import weakref
|
| 17 |
+
|
| 18 |
+
from . import events
|
| 19 |
+
from . import base_subprocess
|
| 20 |
+
from . import futures
|
| 21 |
+
from . import exceptions
|
| 22 |
+
from . import proactor_events
|
| 23 |
+
from . import selector_events
|
| 24 |
+
from . import tasks
|
| 25 |
+
from . import windows_utils
|
| 26 |
+
from .log import logger
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
__all__ = (
|
| 30 |
+
'SelectorEventLoop', 'ProactorEventLoop', 'IocpProactor',
|
| 31 |
+
'DefaultEventLoopPolicy', 'WindowsSelectorEventLoopPolicy',
|
| 32 |
+
'WindowsProactorEventLoopPolicy',
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
NULL = _winapi.NULL
|
| 37 |
+
INFINITE = _winapi.INFINITE
|
| 38 |
+
ERROR_CONNECTION_REFUSED = 1225
|
| 39 |
+
ERROR_CONNECTION_ABORTED = 1236
|
| 40 |
+
|
| 41 |
+
# Initial delay in seconds for connect_pipe() before retrying to connect
|
| 42 |
+
CONNECT_PIPE_INIT_DELAY = 0.001
|
| 43 |
+
|
| 44 |
+
# Maximum delay in seconds for connect_pipe() before retrying to connect
|
| 45 |
+
CONNECT_PIPE_MAX_DELAY = 0.100
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class _OverlappedFuture(futures.Future):
|
| 49 |
+
"""Subclass of Future which represents an overlapped operation.
|
| 50 |
+
|
| 51 |
+
Cancelling it will immediately cancel the overlapped operation.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, ov, *, loop=None):
|
| 55 |
+
super().__init__(loop=loop)
|
| 56 |
+
if self._source_traceback:
|
| 57 |
+
del self._source_traceback[-1]
|
| 58 |
+
self._ov = ov
|
| 59 |
+
|
| 60 |
+
def _repr_info(self):
|
| 61 |
+
info = super()._repr_info()
|
| 62 |
+
if self._ov is not None:
|
| 63 |
+
state = 'pending' if self._ov.pending else 'completed'
|
| 64 |
+
info.insert(1, f'overlapped=<{state}, {self._ov.address:#x}>')
|
| 65 |
+
return info
|
| 66 |
+
|
| 67 |
+
def _cancel_overlapped(self):
|
| 68 |
+
if self._ov is None:
|
| 69 |
+
return
|
| 70 |
+
try:
|
| 71 |
+
self._ov.cancel()
|
| 72 |
+
except OSError as exc:
|
| 73 |
+
context = {
|
| 74 |
+
'message': 'Cancelling an overlapped future failed',
|
| 75 |
+
'exception': exc,
|
| 76 |
+
'future': self,
|
| 77 |
+
}
|
| 78 |
+
if self._source_traceback:
|
| 79 |
+
context['source_traceback'] = self._source_traceback
|
| 80 |
+
self._loop.call_exception_handler(context)
|
| 81 |
+
self._ov = None
|
| 82 |
+
|
| 83 |
+
def cancel(self, msg=None):
|
| 84 |
+
self._cancel_overlapped()
|
| 85 |
+
return super().cancel(msg=msg)
|
| 86 |
+
|
| 87 |
+
def set_exception(self, exception):
|
| 88 |
+
super().set_exception(exception)
|
| 89 |
+
self._cancel_overlapped()
|
| 90 |
+
|
| 91 |
+
def set_result(self, result):
|
| 92 |
+
super().set_result(result)
|
| 93 |
+
self._ov = None
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class _BaseWaitHandleFuture(futures.Future):
|
| 97 |
+
"""Subclass of Future which represents a wait handle."""
|
| 98 |
+
|
| 99 |
+
def __init__(self, ov, handle, wait_handle, *, loop=None):
|
| 100 |
+
super().__init__(loop=loop)
|
| 101 |
+
if self._source_traceback:
|
| 102 |
+
del self._source_traceback[-1]
|
| 103 |
+
# Keep a reference to the Overlapped object to keep it alive until the
|
| 104 |
+
# wait is unregistered
|
| 105 |
+
self._ov = ov
|
| 106 |
+
self._handle = handle
|
| 107 |
+
self._wait_handle = wait_handle
|
| 108 |
+
|
| 109 |
+
# Should we call UnregisterWaitEx() if the wait completes
|
| 110 |
+
# or is cancelled?
|
| 111 |
+
self._registered = True
|
| 112 |
+
|
| 113 |
+
def _poll(self):
|
| 114 |
+
# non-blocking wait: use a timeout of 0 millisecond
|
| 115 |
+
return (_winapi.WaitForSingleObject(self._handle, 0) ==
|
| 116 |
+
_winapi.WAIT_OBJECT_0)
|
| 117 |
+
|
| 118 |
+
def _repr_info(self):
|
| 119 |
+
info = super()._repr_info()
|
| 120 |
+
info.append(f'handle={self._handle:#x}')
|
| 121 |
+
if self._handle is not None:
|
| 122 |
+
state = 'signaled' if self._poll() else 'waiting'
|
| 123 |
+
info.append(state)
|
| 124 |
+
if self._wait_handle is not None:
|
| 125 |
+
info.append(f'wait_handle={self._wait_handle:#x}')
|
| 126 |
+
return info
|
| 127 |
+
|
| 128 |
+
def _unregister_wait_cb(self, fut):
|
| 129 |
+
# The wait was unregistered: it's not safe to destroy the Overlapped
|
| 130 |
+
# object
|
| 131 |
+
self._ov = None
|
| 132 |
+
|
| 133 |
+
def _unregister_wait(self):
|
| 134 |
+
if not self._registered:
|
| 135 |
+
return
|
| 136 |
+
self._registered = False
|
| 137 |
+
|
| 138 |
+
wait_handle = self._wait_handle
|
| 139 |
+
self._wait_handle = None
|
| 140 |
+
try:
|
| 141 |
+
_overlapped.UnregisterWait(wait_handle)
|
| 142 |
+
except OSError as exc:
|
| 143 |
+
if exc.winerror != _overlapped.ERROR_IO_PENDING:
|
| 144 |
+
context = {
|
| 145 |
+
'message': 'Failed to unregister the wait handle',
|
| 146 |
+
'exception': exc,
|
| 147 |
+
'future': self,
|
| 148 |
+
}
|
| 149 |
+
if self._source_traceback:
|
| 150 |
+
context['source_traceback'] = self._source_traceback
|
| 151 |
+
self._loop.call_exception_handler(context)
|
| 152 |
+
return
|
| 153 |
+
# ERROR_IO_PENDING means that the unregister is pending
|
| 154 |
+
|
| 155 |
+
self._unregister_wait_cb(None)
|
| 156 |
+
|
| 157 |
+
def cancel(self, msg=None):
|
| 158 |
+
self._unregister_wait()
|
| 159 |
+
return super().cancel(msg=msg)
|
| 160 |
+
|
| 161 |
+
def set_exception(self, exception):
|
| 162 |
+
self._unregister_wait()
|
| 163 |
+
super().set_exception(exception)
|
| 164 |
+
|
| 165 |
+
def set_result(self, result):
|
| 166 |
+
self._unregister_wait()
|
| 167 |
+
super().set_result(result)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class _WaitCancelFuture(_BaseWaitHandleFuture):
|
| 171 |
+
"""Subclass of Future which represents a wait for the cancellation of a
|
| 172 |
+
_WaitHandleFuture using an event.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
def __init__(self, ov, event, wait_handle, *, loop=None):
|
| 176 |
+
super().__init__(ov, event, wait_handle, loop=loop)
|
| 177 |
+
|
| 178 |
+
self._done_callback = None
|
| 179 |
+
|
| 180 |
+
def cancel(self):
|
| 181 |
+
raise RuntimeError("_WaitCancelFuture must not be cancelled")
|
| 182 |
+
|
| 183 |
+
def set_result(self, result):
|
| 184 |
+
super().set_result(result)
|
| 185 |
+
if self._done_callback is not None:
|
| 186 |
+
self._done_callback(self)
|
| 187 |
+
|
| 188 |
+
def set_exception(self, exception):
|
| 189 |
+
super().set_exception(exception)
|
| 190 |
+
if self._done_callback is not None:
|
| 191 |
+
self._done_callback(self)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class _WaitHandleFuture(_BaseWaitHandleFuture):
|
| 195 |
+
def __init__(self, ov, handle, wait_handle, proactor, *, loop=None):
|
| 196 |
+
super().__init__(ov, handle, wait_handle, loop=loop)
|
| 197 |
+
self._proactor = proactor
|
| 198 |
+
self._unregister_proactor = True
|
| 199 |
+
self._event = _overlapped.CreateEvent(None, True, False, None)
|
| 200 |
+
self._event_fut = None
|
| 201 |
+
|
| 202 |
+
def _unregister_wait_cb(self, fut):
|
| 203 |
+
if self._event is not None:
|
| 204 |
+
_winapi.CloseHandle(self._event)
|
| 205 |
+
self._event = None
|
| 206 |
+
self._event_fut = None
|
| 207 |
+
|
| 208 |
+
# If the wait was cancelled, the wait may never be signalled, so
|
| 209 |
+
# it's required to unregister it. Otherwise, IocpProactor.close() will
|
| 210 |
+
# wait forever for an event which will never come.
|
| 211 |
+
#
|
| 212 |
+
# If the IocpProactor already received the event, it's safe to call
|
| 213 |
+
# _unregister() because we kept a reference to the Overlapped object
|
| 214 |
+
# which is used as a unique key.
|
| 215 |
+
self._proactor._unregister(self._ov)
|
| 216 |
+
self._proactor = None
|
| 217 |
+
|
| 218 |
+
super()._unregister_wait_cb(fut)
|
| 219 |
+
|
| 220 |
+
def _unregister_wait(self):
|
| 221 |
+
if not self._registered:
|
| 222 |
+
return
|
| 223 |
+
self._registered = False
|
| 224 |
+
|
| 225 |
+
wait_handle = self._wait_handle
|
| 226 |
+
self._wait_handle = None
|
| 227 |
+
try:
|
| 228 |
+
_overlapped.UnregisterWaitEx(wait_handle, self._event)
|
| 229 |
+
except OSError as exc:
|
| 230 |
+
if exc.winerror != _overlapped.ERROR_IO_PENDING:
|
| 231 |
+
context = {
|
| 232 |
+
'message': 'Failed to unregister the wait handle',
|
| 233 |
+
'exception': exc,
|
| 234 |
+
'future': self,
|
| 235 |
+
}
|
| 236 |
+
if self._source_traceback:
|
| 237 |
+
context['source_traceback'] = self._source_traceback
|
| 238 |
+
self._loop.call_exception_handler(context)
|
| 239 |
+
return
|
| 240 |
+
# ERROR_IO_PENDING is not an error, the wait was unregistered
|
| 241 |
+
|
| 242 |
+
self._event_fut = self._proactor._wait_cancel(self._event,
|
| 243 |
+
self._unregister_wait_cb)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class PipeServer(object):
|
| 247 |
+
"""Class representing a pipe server.
|
| 248 |
+
|
| 249 |
+
This is much like a bound, listening socket.
|
| 250 |
+
"""
|
| 251 |
+
def __init__(self, address):
|
| 252 |
+
self._address = address
|
| 253 |
+
self._free_instances = weakref.WeakSet()
|
| 254 |
+
# initialize the pipe attribute before calling _server_pipe_handle()
|
| 255 |
+
# because this function can raise an exception and the destructor calls
|
| 256 |
+
# the close() method
|
| 257 |
+
self._pipe = None
|
| 258 |
+
self._accept_pipe_future = None
|
| 259 |
+
self._pipe = self._server_pipe_handle(True)
|
| 260 |
+
|
| 261 |
+
def _get_unconnected_pipe(self):
|
| 262 |
+
# Create new instance and return previous one. This ensures
|
| 263 |
+
# that (until the server is closed) there is always at least
|
| 264 |
+
# one pipe handle for address. Therefore if a client attempt
|
| 265 |
+
# to connect it will not fail with FileNotFoundError.
|
| 266 |
+
tmp, self._pipe = self._pipe, self._server_pipe_handle(False)
|
| 267 |
+
return tmp
|
| 268 |
+
|
| 269 |
+
def _server_pipe_handle(self, first):
|
| 270 |
+
# Return a wrapper for a new pipe handle.
|
| 271 |
+
if self.closed():
|
| 272 |
+
return None
|
| 273 |
+
flags = _winapi.PIPE_ACCESS_DUPLEX | _winapi.FILE_FLAG_OVERLAPPED
|
| 274 |
+
if first:
|
| 275 |
+
flags |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
|
| 276 |
+
h = _winapi.CreateNamedPipe(
|
| 277 |
+
self._address, flags,
|
| 278 |
+
_winapi.PIPE_TYPE_MESSAGE | _winapi.PIPE_READMODE_MESSAGE |
|
| 279 |
+
_winapi.PIPE_WAIT,
|
| 280 |
+
_winapi.PIPE_UNLIMITED_INSTANCES,
|
| 281 |
+
windows_utils.BUFSIZE, windows_utils.BUFSIZE,
|
| 282 |
+
_winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)
|
| 283 |
+
pipe = windows_utils.PipeHandle(h)
|
| 284 |
+
self._free_instances.add(pipe)
|
| 285 |
+
return pipe
|
| 286 |
+
|
| 287 |
+
def closed(self):
|
| 288 |
+
return (self._address is None)
|
| 289 |
+
|
| 290 |
+
def close(self):
|
| 291 |
+
if self._accept_pipe_future is not None:
|
| 292 |
+
self._accept_pipe_future.cancel()
|
| 293 |
+
self._accept_pipe_future = None
|
| 294 |
+
# Close all instances which have not been connected to by a client.
|
| 295 |
+
if self._address is not None:
|
| 296 |
+
for pipe in self._free_instances:
|
| 297 |
+
pipe.close()
|
| 298 |
+
self._pipe = None
|
| 299 |
+
self._address = None
|
| 300 |
+
self._free_instances.clear()
|
| 301 |
+
|
| 302 |
+
__del__ = close
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop):
|
| 306 |
+
"""Windows version of selector event loop."""
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class ProactorEventLoop(proactor_events.BaseProactorEventLoop):
|
| 310 |
+
"""Windows version of proactor event loop using IOCP."""
|
| 311 |
+
|
| 312 |
+
def __init__(self, proactor=None):
|
| 313 |
+
if proactor is None:
|
| 314 |
+
proactor = IocpProactor()
|
| 315 |
+
super().__init__(proactor)
|
| 316 |
+
|
| 317 |
+
def run_forever(self):
|
| 318 |
+
try:
|
| 319 |
+
assert self._self_reading_future is None
|
| 320 |
+
self.call_soon(self._loop_self_reading)
|
| 321 |
+
super().run_forever()
|
| 322 |
+
finally:
|
| 323 |
+
if self._self_reading_future is not None:
|
| 324 |
+
ov = self._self_reading_future._ov
|
| 325 |
+
self._self_reading_future.cancel()
|
| 326 |
+
# self_reading_future always uses IOCP, so even though it's
|
| 327 |
+
# been cancelled, we need to make sure that the IOCP message
|
| 328 |
+
# is received so that the kernel is not holding on to the
|
| 329 |
+
# memory, possibly causing memory corruption later. Only
|
| 330 |
+
# unregister it if IO is complete in all respects. Otherwise
|
| 331 |
+
# we need another _poll() later to complete the IO.
|
| 332 |
+
if ov is not None and not ov.pending:
|
| 333 |
+
self._proactor._unregister(ov)
|
| 334 |
+
self._self_reading_future = None
|
| 335 |
+
|
| 336 |
+
async def create_pipe_connection(self, protocol_factory, address):
|
| 337 |
+
f = self._proactor.connect_pipe(address)
|
| 338 |
+
pipe = await f
|
| 339 |
+
protocol = protocol_factory()
|
| 340 |
+
trans = self._make_duplex_pipe_transport(pipe, protocol,
|
| 341 |
+
extra={'addr': address})
|
| 342 |
+
return trans, protocol
|
| 343 |
+
|
| 344 |
+
async def start_serving_pipe(self, protocol_factory, address):
|
| 345 |
+
server = PipeServer(address)
|
| 346 |
+
|
| 347 |
+
def loop_accept_pipe(f=None):
|
| 348 |
+
pipe = None
|
| 349 |
+
try:
|
| 350 |
+
if f:
|
| 351 |
+
pipe = f.result()
|
| 352 |
+
server._free_instances.discard(pipe)
|
| 353 |
+
|
| 354 |
+
if server.closed():
|
| 355 |
+
# A client connected before the server was closed:
|
| 356 |
+
# drop the client (close the pipe) and exit
|
| 357 |
+
pipe.close()
|
| 358 |
+
return
|
| 359 |
+
|
| 360 |
+
protocol = protocol_factory()
|
| 361 |
+
self._make_duplex_pipe_transport(
|
| 362 |
+
pipe, protocol, extra={'addr': address})
|
| 363 |
+
|
| 364 |
+
pipe = server._get_unconnected_pipe()
|
| 365 |
+
if pipe is None:
|
| 366 |
+
return
|
| 367 |
+
|
| 368 |
+
f = self._proactor.accept_pipe(pipe)
|
| 369 |
+
except BrokenPipeError:
|
| 370 |
+
if pipe and pipe.fileno() != -1:
|
| 371 |
+
pipe.close()
|
| 372 |
+
self.call_soon(loop_accept_pipe)
|
| 373 |
+
except OSError as exc:
|
| 374 |
+
if pipe and pipe.fileno() != -1:
|
| 375 |
+
self.call_exception_handler({
|
| 376 |
+
'message': 'Pipe accept failed',
|
| 377 |
+
'exception': exc,
|
| 378 |
+
'pipe': pipe,
|
| 379 |
+
})
|
| 380 |
+
pipe.close()
|
| 381 |
+
elif self._debug:
|
| 382 |
+
logger.warning("Accept pipe failed on pipe %r",
|
| 383 |
+
pipe, exc_info=True)
|
| 384 |
+
self.call_soon(loop_accept_pipe)
|
| 385 |
+
except exceptions.CancelledError:
|
| 386 |
+
if pipe:
|
| 387 |
+
pipe.close()
|
| 388 |
+
else:
|
| 389 |
+
server._accept_pipe_future = f
|
| 390 |
+
f.add_done_callback(loop_accept_pipe)
|
| 391 |
+
|
| 392 |
+
self.call_soon(loop_accept_pipe)
|
| 393 |
+
return [server]
|
| 394 |
+
|
| 395 |
+
async def _make_subprocess_transport(self, protocol, args, shell,
|
| 396 |
+
stdin, stdout, stderr, bufsize,
|
| 397 |
+
extra=None, **kwargs):
|
| 398 |
+
waiter = self.create_future()
|
| 399 |
+
transp = _WindowsSubprocessTransport(self, protocol, args, shell,
|
| 400 |
+
stdin, stdout, stderr, bufsize,
|
| 401 |
+
waiter=waiter, extra=extra,
|
| 402 |
+
**kwargs)
|
| 403 |
+
try:
|
| 404 |
+
await waiter
|
| 405 |
+
except (SystemExit, KeyboardInterrupt):
|
| 406 |
+
raise
|
| 407 |
+
except BaseException:
|
| 408 |
+
transp.close()
|
| 409 |
+
await transp._wait()
|
| 410 |
+
raise
|
| 411 |
+
|
| 412 |
+
return transp
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
class IocpProactor:
|
| 416 |
+
"""Proactor implementation using IOCP."""
|
| 417 |
+
|
| 418 |
+
def __init__(self, concurrency=INFINITE):
|
| 419 |
+
self._loop = None
|
| 420 |
+
self._results = []
|
| 421 |
+
self._iocp = _overlapped.CreateIoCompletionPort(
|
| 422 |
+
_overlapped.INVALID_HANDLE_VALUE, NULL, 0, concurrency)
|
| 423 |
+
self._cache = {}
|
| 424 |
+
self._registered = weakref.WeakSet()
|
| 425 |
+
self._unregistered = []
|
| 426 |
+
self._stopped_serving = weakref.WeakSet()
|
| 427 |
+
|
| 428 |
+
def _check_closed(self):
|
| 429 |
+
if self._iocp is None:
|
| 430 |
+
raise RuntimeError('IocpProactor is closed')
|
| 431 |
+
|
| 432 |
+
def __repr__(self):
|
| 433 |
+
info = ['overlapped#=%s' % len(self._cache),
|
| 434 |
+
'result#=%s' % len(self._results)]
|
| 435 |
+
if self._iocp is None:
|
| 436 |
+
info.append('closed')
|
| 437 |
+
return '<%s %s>' % (self.__class__.__name__, " ".join(info))
|
| 438 |
+
|
| 439 |
+
def set_loop(self, loop):
|
| 440 |
+
self._loop = loop
|
| 441 |
+
|
| 442 |
+
def select(self, timeout=None):
|
| 443 |
+
if not self._results:
|
| 444 |
+
self._poll(timeout)
|
| 445 |
+
tmp = self._results
|
| 446 |
+
self._results = []
|
| 447 |
+
try:
|
| 448 |
+
return tmp
|
| 449 |
+
finally:
|
| 450 |
+
# Needed to break cycles when an exception occurs.
|
| 451 |
+
tmp = None
|
| 452 |
+
|
| 453 |
+
def _result(self, value):
|
| 454 |
+
fut = self._loop.create_future()
|
| 455 |
+
fut.set_result(value)
|
| 456 |
+
return fut
|
| 457 |
+
|
| 458 |
+
def recv(self, conn, nbytes, flags=0):
|
| 459 |
+
self._register_with_iocp(conn)
|
| 460 |
+
ov = _overlapped.Overlapped(NULL)
|
| 461 |
+
try:
|
| 462 |
+
if isinstance(conn, socket.socket):
|
| 463 |
+
ov.WSARecv(conn.fileno(), nbytes, flags)
|
| 464 |
+
else:
|
| 465 |
+
ov.ReadFile(conn.fileno(), nbytes)
|
| 466 |
+
except BrokenPipeError:
|
| 467 |
+
return self._result(b'')
|
| 468 |
+
|
| 469 |
+
def finish_recv(trans, key, ov):
|
| 470 |
+
try:
|
| 471 |
+
return ov.getresult()
|
| 472 |
+
except OSError as exc:
|
| 473 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 474 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 475 |
+
raise ConnectionResetError(*exc.args)
|
| 476 |
+
else:
|
| 477 |
+
raise
|
| 478 |
+
|
| 479 |
+
return self._register(ov, conn, finish_recv)
|
| 480 |
+
|
| 481 |
+
def recv_into(self, conn, buf, flags=0):
|
| 482 |
+
self._register_with_iocp(conn)
|
| 483 |
+
ov = _overlapped.Overlapped(NULL)
|
| 484 |
+
try:
|
| 485 |
+
if isinstance(conn, socket.socket):
|
| 486 |
+
ov.WSARecvInto(conn.fileno(), buf, flags)
|
| 487 |
+
else:
|
| 488 |
+
ov.ReadFileInto(conn.fileno(), buf)
|
| 489 |
+
except BrokenPipeError:
|
| 490 |
+
return self._result(0)
|
| 491 |
+
|
| 492 |
+
def finish_recv(trans, key, ov):
|
| 493 |
+
try:
|
| 494 |
+
return ov.getresult()
|
| 495 |
+
except OSError as exc:
|
| 496 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 497 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 498 |
+
raise ConnectionResetError(*exc.args)
|
| 499 |
+
else:
|
| 500 |
+
raise
|
| 501 |
+
|
| 502 |
+
return self._register(ov, conn, finish_recv)
|
| 503 |
+
|
| 504 |
+
def recvfrom(self, conn, nbytes, flags=0):
|
| 505 |
+
self._register_with_iocp(conn)
|
| 506 |
+
ov = _overlapped.Overlapped(NULL)
|
| 507 |
+
try:
|
| 508 |
+
ov.WSARecvFrom(conn.fileno(), nbytes, flags)
|
| 509 |
+
except BrokenPipeError:
|
| 510 |
+
return self._result((b'', None))
|
| 511 |
+
|
| 512 |
+
def finish_recv(trans, key, ov):
|
| 513 |
+
try:
|
| 514 |
+
return ov.getresult()
|
| 515 |
+
except OSError as exc:
|
| 516 |
+
# WSARecvFrom will report ERROR_PORT_UNREACHABLE when the same
|
| 517 |
+
# socket is used to send to an address that is not listening.
|
| 518 |
+
if exc.winerror == _overlapped.ERROR_PORT_UNREACHABLE:
|
| 519 |
+
return b'', None
|
| 520 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 521 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 522 |
+
raise ConnectionResetError(*exc.args)
|
| 523 |
+
else:
|
| 524 |
+
raise
|
| 525 |
+
|
| 526 |
+
return self._register(ov, conn, finish_recv)
|
| 527 |
+
|
| 528 |
+
def recvfrom_into(self, conn, buf, flags=0):
|
| 529 |
+
self._register_with_iocp(conn)
|
| 530 |
+
ov = _overlapped.Overlapped(NULL)
|
| 531 |
+
try:
|
| 532 |
+
ov.WSARecvFromInto(conn.fileno(), buf, flags)
|
| 533 |
+
except BrokenPipeError:
|
| 534 |
+
return self._result((0, None))
|
| 535 |
+
|
| 536 |
+
def finish_recv(trans, key, ov):
|
| 537 |
+
try:
|
| 538 |
+
return ov.getresult()
|
| 539 |
+
except OSError as exc:
|
| 540 |
+
# WSARecvFrom will report ERROR_PORT_UNREACHABLE when the same
|
| 541 |
+
# socket is used to send to an address that is not listening.
|
| 542 |
+
if exc.winerror == _overlapped.ERROR_PORT_UNREACHABLE:
|
| 543 |
+
return 0, None
|
| 544 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 545 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 546 |
+
raise ConnectionResetError(*exc.args)
|
| 547 |
+
else:
|
| 548 |
+
raise
|
| 549 |
+
|
| 550 |
+
return self._register(ov, conn, finish_recv)
|
| 551 |
+
|
| 552 |
+
def sendto(self, conn, buf, flags=0, addr=None):
|
| 553 |
+
self._register_with_iocp(conn)
|
| 554 |
+
ov = _overlapped.Overlapped(NULL)
|
| 555 |
+
|
| 556 |
+
ov.WSASendTo(conn.fileno(), buf, flags, addr)
|
| 557 |
+
|
| 558 |
+
def finish_send(trans, key, ov):
|
| 559 |
+
try:
|
| 560 |
+
return ov.getresult()
|
| 561 |
+
except OSError as exc:
|
| 562 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 563 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 564 |
+
raise ConnectionResetError(*exc.args)
|
| 565 |
+
else:
|
| 566 |
+
raise
|
| 567 |
+
|
| 568 |
+
return self._register(ov, conn, finish_send)
|
| 569 |
+
|
| 570 |
+
def send(self, conn, buf, flags=0):
|
| 571 |
+
self._register_with_iocp(conn)
|
| 572 |
+
ov = _overlapped.Overlapped(NULL)
|
| 573 |
+
if isinstance(conn, socket.socket):
|
| 574 |
+
ov.WSASend(conn.fileno(), buf, flags)
|
| 575 |
+
else:
|
| 576 |
+
ov.WriteFile(conn.fileno(), buf)
|
| 577 |
+
|
| 578 |
+
def finish_send(trans, key, ov):
|
| 579 |
+
try:
|
| 580 |
+
return ov.getresult()
|
| 581 |
+
except OSError as exc:
|
| 582 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 583 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 584 |
+
raise ConnectionResetError(*exc.args)
|
| 585 |
+
else:
|
| 586 |
+
raise
|
| 587 |
+
|
| 588 |
+
return self._register(ov, conn, finish_send)
|
| 589 |
+
|
| 590 |
+
def accept(self, listener):
|
| 591 |
+
self._register_with_iocp(listener)
|
| 592 |
+
conn = self._get_accept_socket(listener.family)
|
| 593 |
+
ov = _overlapped.Overlapped(NULL)
|
| 594 |
+
ov.AcceptEx(listener.fileno(), conn.fileno())
|
| 595 |
+
|
| 596 |
+
def finish_accept(trans, key, ov):
|
| 597 |
+
ov.getresult()
|
| 598 |
+
# Use SO_UPDATE_ACCEPT_CONTEXT so getsockname() etc work.
|
| 599 |
+
buf = struct.pack('@P', listener.fileno())
|
| 600 |
+
conn.setsockopt(socket.SOL_SOCKET,
|
| 601 |
+
_overlapped.SO_UPDATE_ACCEPT_CONTEXT, buf)
|
| 602 |
+
conn.settimeout(listener.gettimeout())
|
| 603 |
+
return conn, conn.getpeername()
|
| 604 |
+
|
| 605 |
+
async def accept_coro(future, conn):
|
| 606 |
+
# Coroutine closing the accept socket if the future is cancelled
|
| 607 |
+
try:
|
| 608 |
+
await future
|
| 609 |
+
except exceptions.CancelledError:
|
| 610 |
+
conn.close()
|
| 611 |
+
raise
|
| 612 |
+
|
| 613 |
+
future = self._register(ov, listener, finish_accept)
|
| 614 |
+
coro = accept_coro(future, conn)
|
| 615 |
+
tasks.ensure_future(coro, loop=self._loop)
|
| 616 |
+
return future
|
| 617 |
+
|
| 618 |
+
def connect(self, conn, address):
|
| 619 |
+
if conn.type == socket.SOCK_DGRAM:
|
| 620 |
+
# WSAConnect will complete immediately for UDP sockets so we don't
|
| 621 |
+
# need to register any IOCP operation
|
| 622 |
+
_overlapped.WSAConnect(conn.fileno(), address)
|
| 623 |
+
fut = self._loop.create_future()
|
| 624 |
+
fut.set_result(None)
|
| 625 |
+
return fut
|
| 626 |
+
|
| 627 |
+
self._register_with_iocp(conn)
|
| 628 |
+
# The socket needs to be locally bound before we call ConnectEx().
|
| 629 |
+
try:
|
| 630 |
+
_overlapped.BindLocal(conn.fileno(), conn.family)
|
| 631 |
+
except OSError as e:
|
| 632 |
+
if e.winerror != errno.WSAEINVAL:
|
| 633 |
+
raise
|
| 634 |
+
# Probably already locally bound; check using getsockname().
|
| 635 |
+
if conn.getsockname()[1] == 0:
|
| 636 |
+
raise
|
| 637 |
+
ov = _overlapped.Overlapped(NULL)
|
| 638 |
+
ov.ConnectEx(conn.fileno(), address)
|
| 639 |
+
|
| 640 |
+
def finish_connect(trans, key, ov):
|
| 641 |
+
ov.getresult()
|
| 642 |
+
# Use SO_UPDATE_CONNECT_CONTEXT so getsockname() etc work.
|
| 643 |
+
conn.setsockopt(socket.SOL_SOCKET,
|
| 644 |
+
_overlapped.SO_UPDATE_CONNECT_CONTEXT, 0)
|
| 645 |
+
return conn
|
| 646 |
+
|
| 647 |
+
return self._register(ov, conn, finish_connect)
|
| 648 |
+
|
| 649 |
+
def sendfile(self, sock, file, offset, count):
|
| 650 |
+
self._register_with_iocp(sock)
|
| 651 |
+
ov = _overlapped.Overlapped(NULL)
|
| 652 |
+
offset_low = offset & 0xffff_ffff
|
| 653 |
+
offset_high = (offset >> 32) & 0xffff_ffff
|
| 654 |
+
ov.TransmitFile(sock.fileno(),
|
| 655 |
+
msvcrt.get_osfhandle(file.fileno()),
|
| 656 |
+
offset_low, offset_high,
|
| 657 |
+
count, 0, 0)
|
| 658 |
+
|
| 659 |
+
def finish_sendfile(trans, key, ov):
|
| 660 |
+
try:
|
| 661 |
+
return ov.getresult()
|
| 662 |
+
except OSError as exc:
|
| 663 |
+
if exc.winerror in (_overlapped.ERROR_NETNAME_DELETED,
|
| 664 |
+
_overlapped.ERROR_OPERATION_ABORTED):
|
| 665 |
+
raise ConnectionResetError(*exc.args)
|
| 666 |
+
else:
|
| 667 |
+
raise
|
| 668 |
+
return self._register(ov, sock, finish_sendfile)
|
| 669 |
+
|
| 670 |
+
def accept_pipe(self, pipe):
|
| 671 |
+
self._register_with_iocp(pipe)
|
| 672 |
+
ov = _overlapped.Overlapped(NULL)
|
| 673 |
+
connected = ov.ConnectNamedPipe(pipe.fileno())
|
| 674 |
+
|
| 675 |
+
if connected:
|
| 676 |
+
# ConnectNamePipe() failed with ERROR_PIPE_CONNECTED which means
|
| 677 |
+
# that the pipe is connected. There is no need to wait for the
|
| 678 |
+
# completion of the connection.
|
| 679 |
+
return self._result(pipe)
|
| 680 |
+
|
| 681 |
+
def finish_accept_pipe(trans, key, ov):
|
| 682 |
+
ov.getresult()
|
| 683 |
+
return pipe
|
| 684 |
+
|
| 685 |
+
return self._register(ov, pipe, finish_accept_pipe)
|
| 686 |
+
|
| 687 |
+
async def connect_pipe(self, address):
|
| 688 |
+
delay = CONNECT_PIPE_INIT_DELAY
|
| 689 |
+
while True:
|
| 690 |
+
# Unfortunately there is no way to do an overlapped connect to
|
| 691 |
+
# a pipe. Call CreateFile() in a loop until it doesn't fail with
|
| 692 |
+
# ERROR_PIPE_BUSY.
|
| 693 |
+
try:
|
| 694 |
+
handle = _overlapped.ConnectPipe(address)
|
| 695 |
+
break
|
| 696 |
+
except OSError as exc:
|
| 697 |
+
if exc.winerror != _overlapped.ERROR_PIPE_BUSY:
|
| 698 |
+
raise
|
| 699 |
+
|
| 700 |
+
# ConnectPipe() failed with ERROR_PIPE_BUSY: retry later
|
| 701 |
+
delay = min(delay * 2, CONNECT_PIPE_MAX_DELAY)
|
| 702 |
+
await tasks.sleep(delay)
|
| 703 |
+
|
| 704 |
+
return windows_utils.PipeHandle(handle)
|
| 705 |
+
|
| 706 |
+
def wait_for_handle(self, handle, timeout=None):
|
| 707 |
+
"""Wait for a handle.
|
| 708 |
+
|
| 709 |
+
Return a Future object. The result of the future is True if the wait
|
| 710 |
+
completed, or False if the wait did not complete (on timeout).
|
| 711 |
+
"""
|
| 712 |
+
return self._wait_for_handle(handle, timeout, False)
|
| 713 |
+
|
| 714 |
+
def _wait_cancel(self, event, done_callback):
|
| 715 |
+
fut = self._wait_for_handle(event, None, True)
|
| 716 |
+
# add_done_callback() cannot be used because the wait may only complete
|
| 717 |
+
# in IocpProactor.close(), while the event loop is not running.
|
| 718 |
+
fut._done_callback = done_callback
|
| 719 |
+
return fut
|
| 720 |
+
|
| 721 |
+
def _wait_for_handle(self, handle, timeout, _is_cancel):
|
| 722 |
+
self._check_closed()
|
| 723 |
+
|
| 724 |
+
if timeout is None:
|
| 725 |
+
ms = _winapi.INFINITE
|
| 726 |
+
else:
|
| 727 |
+
# RegisterWaitForSingleObject() has a resolution of 1 millisecond,
|
| 728 |
+
# round away from zero to wait *at least* timeout seconds.
|
| 729 |
+
ms = math.ceil(timeout * 1e3)
|
| 730 |
+
|
| 731 |
+
# We only create ov so we can use ov.address as a key for the cache.
|
| 732 |
+
ov = _overlapped.Overlapped(NULL)
|
| 733 |
+
wait_handle = _overlapped.RegisterWaitWithQueue(
|
| 734 |
+
handle, self._iocp, ov.address, ms)
|
| 735 |
+
if _is_cancel:
|
| 736 |
+
f = _WaitCancelFuture(ov, handle, wait_handle, loop=self._loop)
|
| 737 |
+
else:
|
| 738 |
+
f = _WaitHandleFuture(ov, handle, wait_handle, self,
|
| 739 |
+
loop=self._loop)
|
| 740 |
+
if f._source_traceback:
|
| 741 |
+
del f._source_traceback[-1]
|
| 742 |
+
|
| 743 |
+
def finish_wait_for_handle(trans, key, ov):
|
| 744 |
+
# Note that this second wait means that we should only use
|
| 745 |
+
# this with handles types where a successful wait has no
|
| 746 |
+
# effect. So events or processes are all right, but locks
|
| 747 |
+
# or semaphores are not. Also note if the handle is
|
| 748 |
+
# signalled and then quickly reset, then we may return
|
| 749 |
+
# False even though we have not timed out.
|
| 750 |
+
return f._poll()
|
| 751 |
+
|
| 752 |
+
self._cache[ov.address] = (f, ov, 0, finish_wait_for_handle)
|
| 753 |
+
return f
|
| 754 |
+
|
| 755 |
+
def _register_with_iocp(self, obj):
|
| 756 |
+
# To get notifications of finished ops on this objects sent to the
|
| 757 |
+
# completion port, were must register the handle.
|
| 758 |
+
if obj not in self._registered:
|
| 759 |
+
self._registered.add(obj)
|
| 760 |
+
_overlapped.CreateIoCompletionPort(obj.fileno(), self._iocp, 0, 0)
|
| 761 |
+
# XXX We could also use SetFileCompletionNotificationModes()
|
| 762 |
+
# to avoid sending notifications to completion port of ops
|
| 763 |
+
# that succeed immediately.
|
| 764 |
+
|
| 765 |
+
def _register(self, ov, obj, callback):
|
| 766 |
+
self._check_closed()
|
| 767 |
+
|
| 768 |
+
# Return a future which will be set with the result of the
|
| 769 |
+
# operation when it completes. The future's value is actually
|
| 770 |
+
# the value returned by callback().
|
| 771 |
+
f = _OverlappedFuture(ov, loop=self._loop)
|
| 772 |
+
if f._source_traceback:
|
| 773 |
+
del f._source_traceback[-1]
|
| 774 |
+
if not ov.pending:
|
| 775 |
+
# The operation has completed, so no need to postpone the
|
| 776 |
+
# work. We cannot take this short cut if we need the
|
| 777 |
+
# NumberOfBytes, CompletionKey values returned by
|
| 778 |
+
# PostQueuedCompletionStatus().
|
| 779 |
+
try:
|
| 780 |
+
value = callback(None, None, ov)
|
| 781 |
+
except OSError as e:
|
| 782 |
+
f.set_exception(e)
|
| 783 |
+
else:
|
| 784 |
+
f.set_result(value)
|
| 785 |
+
# Even if GetOverlappedResult() was called, we have to wait for the
|
| 786 |
+
# notification of the completion in GetQueuedCompletionStatus().
|
| 787 |
+
# Register the overlapped operation to keep a reference to the
|
| 788 |
+
# OVERLAPPED object, otherwise the memory is freed and Windows may
|
| 789 |
+
# read uninitialized memory.
|
| 790 |
+
|
| 791 |
+
# Register the overlapped operation for later. Note that
|
| 792 |
+
# we only store obj to prevent it from being garbage
|
| 793 |
+
# collected too early.
|
| 794 |
+
self._cache[ov.address] = (f, ov, obj, callback)
|
| 795 |
+
return f
|
| 796 |
+
|
| 797 |
+
def _unregister(self, ov):
|
| 798 |
+
"""Unregister an overlapped object.
|
| 799 |
+
|
| 800 |
+
Call this method when its future has been cancelled. The event can
|
| 801 |
+
already be signalled (pending in the proactor event queue). It is also
|
| 802 |
+
safe if the event is never signalled (because it was cancelled).
|
| 803 |
+
"""
|
| 804 |
+
self._check_closed()
|
| 805 |
+
self._unregistered.append(ov)
|
| 806 |
+
|
| 807 |
+
def _get_accept_socket(self, family):
|
| 808 |
+
s = socket.socket(family)
|
| 809 |
+
s.settimeout(0)
|
| 810 |
+
return s
|
| 811 |
+
|
| 812 |
+
def _poll(self, timeout=None):
|
| 813 |
+
if timeout is None:
|
| 814 |
+
ms = INFINITE
|
| 815 |
+
elif timeout < 0:
|
| 816 |
+
raise ValueError("negative timeout")
|
| 817 |
+
else:
|
| 818 |
+
# GetQueuedCompletionStatus() has a resolution of 1 millisecond,
|
| 819 |
+
# round away from zero to wait *at least* timeout seconds.
|
| 820 |
+
ms = math.ceil(timeout * 1e3)
|
| 821 |
+
if ms >= INFINITE:
|
| 822 |
+
raise ValueError("timeout too big")
|
| 823 |
+
|
| 824 |
+
while True:
|
| 825 |
+
status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)
|
| 826 |
+
if status is None:
|
| 827 |
+
break
|
| 828 |
+
ms = 0
|
| 829 |
+
|
| 830 |
+
err, transferred, key, address = status
|
| 831 |
+
try:
|
| 832 |
+
f, ov, obj, callback = self._cache.pop(address)
|
| 833 |
+
except KeyError:
|
| 834 |
+
if self._loop.get_debug():
|
| 835 |
+
self._loop.call_exception_handler({
|
| 836 |
+
'message': ('GetQueuedCompletionStatus() returned an '
|
| 837 |
+
'unexpected event'),
|
| 838 |
+
'status': ('err=%s transferred=%s key=%#x address=%#x'
|
| 839 |
+
% (err, transferred, key, address)),
|
| 840 |
+
})
|
| 841 |
+
|
| 842 |
+
# key is either zero, or it is used to return a pipe
|
| 843 |
+
# handle which should be closed to avoid a leak.
|
| 844 |
+
if key not in (0, _overlapped.INVALID_HANDLE_VALUE):
|
| 845 |
+
_winapi.CloseHandle(key)
|
| 846 |
+
continue
|
| 847 |
+
|
| 848 |
+
if obj in self._stopped_serving:
|
| 849 |
+
f.cancel()
|
| 850 |
+
# Don't call the callback if _register() already read the result or
|
| 851 |
+
# if the overlapped has been cancelled
|
| 852 |
+
elif not f.done():
|
| 853 |
+
try:
|
| 854 |
+
value = callback(transferred, key, ov)
|
| 855 |
+
except OSError as e:
|
| 856 |
+
f.set_exception(e)
|
| 857 |
+
self._results.append(f)
|
| 858 |
+
else:
|
| 859 |
+
f.set_result(value)
|
| 860 |
+
self._results.append(f)
|
| 861 |
+
finally:
|
| 862 |
+
f = None
|
| 863 |
+
|
| 864 |
+
# Remove unregistered futures
|
| 865 |
+
for ov in self._unregistered:
|
| 866 |
+
self._cache.pop(ov.address, None)
|
| 867 |
+
self._unregistered.clear()
|
| 868 |
+
|
| 869 |
+
def _stop_serving(self, obj):
|
| 870 |
+
# obj is a socket or pipe handle. It will be closed in
|
| 871 |
+
# BaseProactorEventLoop._stop_serving() which will make any
|
| 872 |
+
# pending operations fail quickly.
|
| 873 |
+
self._stopped_serving.add(obj)
|
| 874 |
+
|
| 875 |
+
def close(self):
|
| 876 |
+
if self._iocp is None:
|
| 877 |
+
# already closed
|
| 878 |
+
return
|
| 879 |
+
|
| 880 |
+
# Cancel remaining registered operations.
|
| 881 |
+
for fut, ov, obj, callback in list(self._cache.values()):
|
| 882 |
+
if fut.cancelled():
|
| 883 |
+
# Nothing to do with cancelled futures
|
| 884 |
+
pass
|
| 885 |
+
elif isinstance(fut, _WaitCancelFuture):
|
| 886 |
+
# _WaitCancelFuture must not be cancelled
|
| 887 |
+
pass
|
| 888 |
+
else:
|
| 889 |
+
try:
|
| 890 |
+
fut.cancel()
|
| 891 |
+
except OSError as exc:
|
| 892 |
+
if self._loop is not None:
|
| 893 |
+
context = {
|
| 894 |
+
'message': 'Cancelling a future failed',
|
| 895 |
+
'exception': exc,
|
| 896 |
+
'future': fut,
|
| 897 |
+
}
|
| 898 |
+
if fut._source_traceback:
|
| 899 |
+
context['source_traceback'] = fut._source_traceback
|
| 900 |
+
self._loop.call_exception_handler(context)
|
| 901 |
+
|
| 902 |
+
# Wait until all cancelled overlapped complete: don't exit with running
|
| 903 |
+
# overlapped to prevent a crash. Display progress every second if the
|
| 904 |
+
# loop is still running.
|
| 905 |
+
msg_update = 1.0
|
| 906 |
+
start_time = time.monotonic()
|
| 907 |
+
next_msg = start_time + msg_update
|
| 908 |
+
while self._cache:
|
| 909 |
+
if next_msg <= time.monotonic():
|
| 910 |
+
logger.debug('%r is running after closing for %.1f seconds',
|
| 911 |
+
self, time.monotonic() - start_time)
|
| 912 |
+
next_msg = time.monotonic() + msg_update
|
| 913 |
+
|
| 914 |
+
# handle a few events, or timeout
|
| 915 |
+
self._poll(msg_update)
|
| 916 |
+
|
| 917 |
+
self._results = []
|
| 918 |
+
|
| 919 |
+
_winapi.CloseHandle(self._iocp)
|
| 920 |
+
self._iocp = None
|
| 921 |
+
|
| 922 |
+
def __del__(self):
|
| 923 |
+
self.close()
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
class _WindowsSubprocessTransport(base_subprocess.BaseSubprocessTransport):
|
| 927 |
+
|
| 928 |
+
def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
|
| 929 |
+
self._proc = windows_utils.Popen(
|
| 930 |
+
args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
|
| 931 |
+
bufsize=bufsize, **kwargs)
|
| 932 |
+
|
| 933 |
+
def callback(f):
|
| 934 |
+
returncode = self._proc.poll()
|
| 935 |
+
self._process_exited(returncode)
|
| 936 |
+
|
| 937 |
+
f = self._loop._proactor.wait_for_handle(int(self._proc._handle))
|
| 938 |
+
f.add_done_callback(callback)
|
| 939 |
+
|
| 940 |
+
|
| 941 |
+
SelectorEventLoop = _WindowsSelectorEventLoop
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
|
| 945 |
+
_loop_factory = SelectorEventLoop
|
| 946 |
+
|
| 947 |
+
|
| 948 |
+
class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
|
| 949 |
+
_loop_factory = ProactorEventLoop
|
| 950 |
+
|
| 951 |
+
|
| 952 |
+
DefaultEventLoopPolicy = WindowsProactorEventLoopPolicy
|
micromamba_root/envs/pytorch_env/Lib/asyncio/windows_utils.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 3 |
+
import sys
|
| 4 |
+
|
| 5 |
+
if sys.platform != 'win32': # pragma: no cover
|
| 6 |
+
raise ImportError('win32 only')
|
| 7 |
+
|
| 8 |
+
import _winapi
|
| 9 |
+
import itertools
|
| 10 |
+
import msvcrt
|
| 11 |
+
import os
|
| 12 |
+
import subprocess
|
| 13 |
+
import tempfile
|
| 14 |
+
import warnings
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
__all__ = 'pipe', 'Popen', 'PIPE', 'PipeHandle'
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# Constants/globals
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
BUFSIZE = 8192
|
| 24 |
+
PIPE = subprocess.PIPE
|
| 25 |
+
STDOUT = subprocess.STDOUT
|
| 26 |
+
_mmap_counter = itertools.count()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# Replacement for os.pipe() using handles instead of fds
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def pipe(*, duplex=False, overlapped=(True, True), bufsize=BUFSIZE):
|
| 33 |
+
"""Like os.pipe() but with overlapped support and using handles not fds."""
|
| 34 |
+
address = tempfile.mktemp(
|
| 35 |
+
prefix=r'\\.\pipe\python-pipe-{:d}-{:d}-'.format(
|
| 36 |
+
os.getpid(), next(_mmap_counter)))
|
| 37 |
+
|
| 38 |
+
if duplex:
|
| 39 |
+
openmode = _winapi.PIPE_ACCESS_DUPLEX
|
| 40 |
+
access = _winapi.GENERIC_READ | _winapi.GENERIC_WRITE
|
| 41 |
+
obsize, ibsize = bufsize, bufsize
|
| 42 |
+
else:
|
| 43 |
+
openmode = _winapi.PIPE_ACCESS_INBOUND
|
| 44 |
+
access = _winapi.GENERIC_WRITE
|
| 45 |
+
obsize, ibsize = 0, bufsize
|
| 46 |
+
|
| 47 |
+
openmode |= _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE
|
| 48 |
+
|
| 49 |
+
if overlapped[0]:
|
| 50 |
+
openmode |= _winapi.FILE_FLAG_OVERLAPPED
|
| 51 |
+
|
| 52 |
+
if overlapped[1]:
|
| 53 |
+
flags_and_attribs = _winapi.FILE_FLAG_OVERLAPPED
|
| 54 |
+
else:
|
| 55 |
+
flags_and_attribs = 0
|
| 56 |
+
|
| 57 |
+
h1 = h2 = None
|
| 58 |
+
try:
|
| 59 |
+
h1 = _winapi.CreateNamedPipe(
|
| 60 |
+
address, openmode, _winapi.PIPE_WAIT,
|
| 61 |
+
1, obsize, ibsize, _winapi.NMPWAIT_WAIT_FOREVER, _winapi.NULL)
|
| 62 |
+
|
| 63 |
+
h2 = _winapi.CreateFile(
|
| 64 |
+
address, access, 0, _winapi.NULL, _winapi.OPEN_EXISTING,
|
| 65 |
+
flags_and_attribs, _winapi.NULL)
|
| 66 |
+
|
| 67 |
+
ov = _winapi.ConnectNamedPipe(h1, overlapped=True)
|
| 68 |
+
ov.GetOverlappedResult(True)
|
| 69 |
+
return h1, h2
|
| 70 |
+
except:
|
| 71 |
+
if h1 is not None:
|
| 72 |
+
_winapi.CloseHandle(h1)
|
| 73 |
+
if h2 is not None:
|
| 74 |
+
_winapi.CloseHandle(h2)
|
| 75 |
+
raise
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# Wrapper for a pipe handle
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class PipeHandle:
|
| 82 |
+
"""Wrapper for an overlapped pipe handle which is vaguely file-object like.
|
| 83 |
+
|
| 84 |
+
The IOCP event loop can use these instead of socket objects.
|
| 85 |
+
"""
|
| 86 |
+
def __init__(self, handle):
|
| 87 |
+
self._handle = handle
|
| 88 |
+
|
| 89 |
+
def __repr__(self):
|
| 90 |
+
if self._handle is not None:
|
| 91 |
+
handle = f'handle={self._handle!r}'
|
| 92 |
+
else:
|
| 93 |
+
handle = 'closed'
|
| 94 |
+
return f'<{self.__class__.__name__} {handle}>'
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def handle(self):
|
| 98 |
+
return self._handle
|
| 99 |
+
|
| 100 |
+
def fileno(self):
|
| 101 |
+
if self._handle is None:
|
| 102 |
+
raise ValueError("I/O operation on closed pipe")
|
| 103 |
+
return self._handle
|
| 104 |
+
|
| 105 |
+
def close(self, *, CloseHandle=_winapi.CloseHandle):
|
| 106 |
+
if self._handle is not None:
|
| 107 |
+
CloseHandle(self._handle)
|
| 108 |
+
self._handle = None
|
| 109 |
+
|
| 110 |
+
def __del__(self, _warn=warnings.warn):
|
| 111 |
+
if self._handle is not None:
|
| 112 |
+
_warn(f"unclosed {self!r}", ResourceWarning, source=self)
|
| 113 |
+
self.close()
|
| 114 |
+
|
| 115 |
+
def __enter__(self):
|
| 116 |
+
return self
|
| 117 |
+
|
| 118 |
+
def __exit__(self, t, v, tb):
|
| 119 |
+
self.close()
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# Replacement for subprocess.Popen using overlapped pipe handles
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class Popen(subprocess.Popen):
|
| 126 |
+
"""Replacement for subprocess.Popen using overlapped pipe handles.
|
| 127 |
+
|
| 128 |
+
The stdin, stdout, stderr are None or instances of PipeHandle.
|
| 129 |
+
"""
|
| 130 |
+
def __init__(self, args, stdin=None, stdout=None, stderr=None, **kwds):
|
| 131 |
+
assert not kwds.get('universal_newlines')
|
| 132 |
+
assert kwds.get('bufsize', 0) == 0
|
| 133 |
+
stdin_rfd = stdout_wfd = stderr_wfd = None
|
| 134 |
+
stdin_wh = stdout_rh = stderr_rh = None
|
| 135 |
+
if stdin == PIPE:
|
| 136 |
+
stdin_rh, stdin_wh = pipe(overlapped=(False, True), duplex=True)
|
| 137 |
+
stdin_rfd = msvcrt.open_osfhandle(stdin_rh, os.O_RDONLY)
|
| 138 |
+
else:
|
| 139 |
+
stdin_rfd = stdin
|
| 140 |
+
if stdout == PIPE:
|
| 141 |
+
stdout_rh, stdout_wh = pipe(overlapped=(True, False))
|
| 142 |
+
stdout_wfd = msvcrt.open_osfhandle(stdout_wh, 0)
|
| 143 |
+
else:
|
| 144 |
+
stdout_wfd = stdout
|
| 145 |
+
if stderr == PIPE:
|
| 146 |
+
stderr_rh, stderr_wh = pipe(overlapped=(True, False))
|
| 147 |
+
stderr_wfd = msvcrt.open_osfhandle(stderr_wh, 0)
|
| 148 |
+
elif stderr == STDOUT:
|
| 149 |
+
stderr_wfd = stdout_wfd
|
| 150 |
+
else:
|
| 151 |
+
stderr_wfd = stderr
|
| 152 |
+
try:
|
| 153 |
+
super().__init__(args, stdin=stdin_rfd, stdout=stdout_wfd,
|
| 154 |
+
stderr=stderr_wfd, **kwds)
|
| 155 |
+
except:
|
| 156 |
+
for h in (stdin_wh, stdout_rh, stderr_rh):
|
| 157 |
+
if h is not None:
|
| 158 |
+
_winapi.CloseHandle(h)
|
| 159 |
+
raise
|
| 160 |
+
else:
|
| 161 |
+
if stdin_wh is not None:
|
| 162 |
+
self.stdin = PipeHandle(stdin_wh)
|
| 163 |
+
if stdout_rh is not None:
|
| 164 |
+
self.stdout = PipeHandle(stdout_rh)
|
| 165 |
+
if stderr_rh is not None:
|
| 166 |
+
self.stderr = PipeHandle(stderr_rh)
|
| 167 |
+
finally:
|
| 168 |
+
if stdin == PIPE:
|
| 169 |
+
os.close(stdin_rfd)
|
| 170 |
+
if stdout == PIPE:
|
| 171 |
+
os.close(stdout_wfd)
|
| 172 |
+
if stderr == PIPE:
|
| 173 |
+
os.close(stderr_wfd)
|
micromamba_root/envs/pytorch_env/Lib/collections/__init__.py
ADDED
|
@@ -0,0 +1,1576 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ements specialized container datatypes providing
|
| 2 |
+
alternatives to Python's general purpose built-in containers, dict,
|
| 3 |
+
list, set, and tuple.
|
| 4 |
+
|
| 5 |
+
* namedtuple factory function for creating tuple subclasses with named fields
|
| 6 |
+
* deque list-like container with fast appends and pops on either end
|
| 7 |
+
* ChainMap dict-like class for creating a single view of multiple mappings
|
| 8 |
+
* Counter dict subclass for counting hashable objects
|
| 9 |
+
* OrderedDict dict subclass that remembers the order entries were added
|
| 10 |
+
* defaultdict dict subclass that calls a factory function to supply missing values
|
| 11 |
+
* UserDict wrapper around dictionary objects for easier dict subclassing
|
| 12 |
+
* UserList wrapper around list objects for easier list subclassing
|
| 13 |
+
* UserString wrapper around string objects for easier string subclassing
|
| 14 |
+
|
| 15 |
+
'''
|
| 16 |
+
|
| 17 |
+
__all__ = [
|
| 18 |
+
'ChainMap',
|
| 19 |
+
'Counter',
|
| 20 |
+
'OrderedDict',
|
| 21 |
+
'UserDict',
|
| 22 |
+
'UserList',
|
| 23 |
+
'UserString',
|
| 24 |
+
'defaultdict',
|
| 25 |
+
'deque',
|
| 26 |
+
'namedtuple',
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
import _collections_abc
|
| 30 |
+
import sys as _sys
|
| 31 |
+
|
| 32 |
+
from itertools import chain as _chain
|
| 33 |
+
from itertools import repeat as _repeat
|
| 34 |
+
from itertools import starmap as _starmap
|
| 35 |
+
from keyword import iskeyword as _iskeyword
|
| 36 |
+
from operator import eq as _eq
|
| 37 |
+
from operator import itemgetter as _itemgetter
|
| 38 |
+
from reprlib import recursive_repr as _recursive_repr
|
| 39 |
+
from _weakref import proxy as _proxy
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
from _collections import deque
|
| 43 |
+
except ImportError:
|
| 44 |
+
pass
|
| 45 |
+
else:
|
| 46 |
+
_collections_abc.MutableSequence.register(deque)
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
from _collections import defaultdict
|
| 50 |
+
except ImportError:
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
################################################################################
|
| 55 |
+
### OrderedDict
|
| 56 |
+
################################################################################
|
| 57 |
+
|
| 58 |
+
class _OrderedDictKeysView(_collections_abc.KeysView):
|
| 59 |
+
|
| 60 |
+
def __reversed__(self):
|
| 61 |
+
yield from reversed(self._mapping)
|
| 62 |
+
|
| 63 |
+
class _OrderedDictItemsView(_collections_abc.ItemsView):
|
| 64 |
+
|
| 65 |
+
def __reversed__(self):
|
| 66 |
+
for key in reversed(self._mapping):
|
| 67 |
+
yield (key, self._mapping[key])
|
| 68 |
+
|
| 69 |
+
class _OrderedDictValuesView(_collections_abc.ValuesView):
|
| 70 |
+
|
| 71 |
+
def __reversed__(self):
|
| 72 |
+
for key in reversed(self._mapping):
|
| 73 |
+
yield self._mapping[key]
|
| 74 |
+
|
| 75 |
+
class _Link(object):
|
| 76 |
+
__slots__ = 'prev', 'next', 'key', '__weakref__'
|
| 77 |
+
|
| 78 |
+
class OrderedDict(dict):
|
| 79 |
+
'Dictionary that remembers insertion order'
|
| 80 |
+
# An inherited dict maps keys to values.
|
| 81 |
+
# The inherited dict provides __getitem__, __len__, __contains__, and get.
|
| 82 |
+
# The remaining methods are order-aware.
|
| 83 |
+
# Big-O running times for all methods are the same as regular dictionaries.
|
| 84 |
+
|
| 85 |
+
# The internal self.__map dict maps keys to links in a doubly linked list.
|
| 86 |
+
# The circular doubly linked list starts and ends with a sentinel element.
|
| 87 |
+
# The sentinel element never gets deleted (this simplifies the algorithm).
|
| 88 |
+
# The sentinel is in self.__hardroot with a weakref proxy in self.__root.
|
| 89 |
+
# The prev links are weakref proxies (to prevent circular references).
|
| 90 |
+
# Individual links are kept alive by the hard reference in self.__map.
|
| 91 |
+
# Those hard references disappear when a key is deleted from an OrderedDict.
|
| 92 |
+
|
| 93 |
+
def __new__(cls, /, *args, **kwds):
|
| 94 |
+
"Create the ordered dict object and set up the underlying structures."
|
| 95 |
+
self = dict.__new__(cls)
|
| 96 |
+
self.__hardroot = _Link()
|
| 97 |
+
self.__root = root = _proxy(self.__hardroot)
|
| 98 |
+
root.prev = root.next = root
|
| 99 |
+
self.__map = {}
|
| 100 |
+
return self
|
| 101 |
+
|
| 102 |
+
def __init__(self, other=(), /, **kwds):
|
| 103 |
+
'''Initialize an ordered dictionary. The signature is the same as
|
| 104 |
+
regular dictionaries. Keyword argument order is preserved.
|
| 105 |
+
'''
|
| 106 |
+
self.__update(other, **kwds)
|
| 107 |
+
|
| 108 |
+
def __setitem__(self, key, value,
|
| 109 |
+
dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
|
| 110 |
+
'od.__setitem__(i, y) <==> od[i]=y'
|
| 111 |
+
# Setting a new item creates a new link at the end of the linked list,
|
| 112 |
+
# and the inherited dictionary is updated with the new key/value pair.
|
| 113 |
+
if key not in self:
|
| 114 |
+
self.__map[key] = link = Link()
|
| 115 |
+
root = self.__root
|
| 116 |
+
last = root.prev
|
| 117 |
+
link.prev, link.next, link.key = last, root, key
|
| 118 |
+
last.next = link
|
| 119 |
+
root.prev = proxy(link)
|
| 120 |
+
dict_setitem(self, key, value)
|
| 121 |
+
|
| 122 |
+
def __delitem__(self, key, dict_delitem=dict.__delitem__):
|
| 123 |
+
'od.__delitem__(y) <==> del od[y]'
|
| 124 |
+
# Deleting an existing item uses self.__map to find the link which gets
|
| 125 |
+
# removed by updating the links in the predecessor and successor nodes.
|
| 126 |
+
dict_delitem(self, key)
|
| 127 |
+
link = self.__map.pop(key)
|
| 128 |
+
link_prev = link.prev
|
| 129 |
+
link_next = link.next
|
| 130 |
+
link_prev.next = link_next
|
| 131 |
+
link_next.prev = link_prev
|
| 132 |
+
link.prev = None
|
| 133 |
+
link.next = None
|
| 134 |
+
|
| 135 |
+
def __iter__(self):
|
| 136 |
+
'od.__iter__() <==> iter(od)'
|
| 137 |
+
# Traverse the linked list in order.
|
| 138 |
+
root = self.__root
|
| 139 |
+
curr = root.next
|
| 140 |
+
while curr is not root:
|
| 141 |
+
yield curr.key
|
| 142 |
+
curr = curr.next
|
| 143 |
+
|
| 144 |
+
def __reversed__(self):
|
| 145 |
+
'od.__reversed__() <==> reversed(od)'
|
| 146 |
+
# Traverse the linked list in reverse order.
|
| 147 |
+
root = self.__root
|
| 148 |
+
curr = root.prev
|
| 149 |
+
while curr is not root:
|
| 150 |
+
yield curr.key
|
| 151 |
+
curr = curr.prev
|
| 152 |
+
|
| 153 |
+
def clear(self):
|
| 154 |
+
'od.clear() -> None. Remove all items from od.'
|
| 155 |
+
root = self.__root
|
| 156 |
+
root.prev = root.next = root
|
| 157 |
+
self.__map.clear()
|
| 158 |
+
dict.clear(self)
|
| 159 |
+
|
| 160 |
+
def popitem(self, last=True):
|
| 161 |
+
'''Remove and return a (key, value) pair from the dictionary.
|
| 162 |
+
|
| 163 |
+
Pairs are returned in LIFO order if last is true or FIFO order if false.
|
| 164 |
+
'''
|
| 165 |
+
if not self:
|
| 166 |
+
raise KeyError('dictionary is empty')
|
| 167 |
+
root = self.__root
|
| 168 |
+
if last:
|
| 169 |
+
link = root.prev
|
| 170 |
+
link_prev = link.prev
|
| 171 |
+
link_prev.next = root
|
| 172 |
+
root.prev = link_prev
|
| 173 |
+
else:
|
| 174 |
+
link = root.next
|
| 175 |
+
link_next = link.next
|
| 176 |
+
root.next = link_next
|
| 177 |
+
link_next.prev = root
|
| 178 |
+
key = link.key
|
| 179 |
+
del self.__map[key]
|
| 180 |
+
value = dict.pop(self, key)
|
| 181 |
+
return key, value
|
| 182 |
+
|
| 183 |
+
def move_to_end(self, key, last=True):
|
| 184 |
+
'''Move an existing element to the end (or beginning if last is false).
|
| 185 |
+
|
| 186 |
+
Raise KeyError if the element does not exist.
|
| 187 |
+
'''
|
| 188 |
+
link = self.__map[key]
|
| 189 |
+
link_prev = link.prev
|
| 190 |
+
link_next = link.next
|
| 191 |
+
soft_link = link_next.prev
|
| 192 |
+
link_prev.next = link_next
|
| 193 |
+
link_next.prev = link_prev
|
| 194 |
+
root = self.__root
|
| 195 |
+
if last:
|
| 196 |
+
last = root.prev
|
| 197 |
+
link.prev = last
|
| 198 |
+
link.next = root
|
| 199 |
+
root.prev = soft_link
|
| 200 |
+
last.next = link
|
| 201 |
+
else:
|
| 202 |
+
first = root.next
|
| 203 |
+
link.prev = root
|
| 204 |
+
link.next = first
|
| 205 |
+
first.prev = soft_link
|
| 206 |
+
root.next = link
|
| 207 |
+
|
| 208 |
+
def __sizeof__(self):
|
| 209 |
+
sizeof = _sys.getsizeof
|
| 210 |
+
n = len(self) + 1 # number of links including root
|
| 211 |
+
size = sizeof(self.__dict__) # instance dictionary
|
| 212 |
+
size += sizeof(self.__map) * 2 # internal dict and inherited dict
|
| 213 |
+
size += sizeof(self.__hardroot) * n # link objects
|
| 214 |
+
size += sizeof(self.__root) * n # proxy objects
|
| 215 |
+
return size
|
| 216 |
+
|
| 217 |
+
update = __update = _collections_abc.MutableMapping.update
|
| 218 |
+
|
| 219 |
+
def keys(self):
|
| 220 |
+
"D.keys() -> a set-like object providing a view on D's keys"
|
| 221 |
+
return _OrderedDictKeysView(self)
|
| 222 |
+
|
| 223 |
+
def items(self):
|
| 224 |
+
"D.items() -> a set-like object providing a view on D's items"
|
| 225 |
+
return _OrderedDictItemsView(self)
|
| 226 |
+
|
| 227 |
+
def values(self):
|
| 228 |
+
"D.values() -> an object providing a view on D's values"
|
| 229 |
+
return _OrderedDictValuesView(self)
|
| 230 |
+
|
| 231 |
+
__ne__ = _collections_abc.MutableMapping.__ne__
|
| 232 |
+
|
| 233 |
+
__marker = object()
|
| 234 |
+
|
| 235 |
+
def pop(self, key, default=__marker):
|
| 236 |
+
'''od.pop(k[,d]) -> v, remove specified key and return the corresponding
|
| 237 |
+
value. If key is not found, d is returned if given, otherwise KeyError
|
| 238 |
+
is raised.
|
| 239 |
+
|
| 240 |
+
'''
|
| 241 |
+
marker = self.__marker
|
| 242 |
+
result = dict.pop(self, key, marker)
|
| 243 |
+
if result is not marker:
|
| 244 |
+
# The same as in __delitem__().
|
| 245 |
+
link = self.__map.pop(key)
|
| 246 |
+
link_prev = link.prev
|
| 247 |
+
link_next = link.next
|
| 248 |
+
link_prev.next = link_next
|
| 249 |
+
link_next.prev = link_prev
|
| 250 |
+
link.prev = None
|
| 251 |
+
link.next = None
|
| 252 |
+
return result
|
| 253 |
+
if default is marker:
|
| 254 |
+
raise KeyError(key)
|
| 255 |
+
return default
|
| 256 |
+
|
| 257 |
+
def setdefault(self, key, default=None):
|
| 258 |
+
'''Insert key with a value of default if key is not in the dictionary.
|
| 259 |
+
|
| 260 |
+
Return the value for key if key is in the dictionary, else default.
|
| 261 |
+
'''
|
| 262 |
+
if key in self:
|
| 263 |
+
return self[key]
|
| 264 |
+
self[key] = default
|
| 265 |
+
return default
|
| 266 |
+
|
| 267 |
+
@_recursive_repr()
|
| 268 |
+
def __repr__(self):
|
| 269 |
+
'od.__repr__() <==> repr(od)'
|
| 270 |
+
if not self:
|
| 271 |
+
return '%s()' % (self.__class__.__name__,)
|
| 272 |
+
return '%s(%r)' % (self.__class__.__name__, list(self.items()))
|
| 273 |
+
|
| 274 |
+
def __reduce__(self):
|
| 275 |
+
'Return state information for pickling'
|
| 276 |
+
state = self.__getstate__()
|
| 277 |
+
if state:
|
| 278 |
+
if isinstance(state, tuple):
|
| 279 |
+
state, slots = state
|
| 280 |
+
else:
|
| 281 |
+
slots = {}
|
| 282 |
+
state = state.copy()
|
| 283 |
+
slots = slots.copy()
|
| 284 |
+
for k in vars(OrderedDict()):
|
| 285 |
+
state.pop(k, None)
|
| 286 |
+
slots.pop(k, None)
|
| 287 |
+
if slots:
|
| 288 |
+
state = state, slots
|
| 289 |
+
else:
|
| 290 |
+
state = state or None
|
| 291 |
+
return self.__class__, (), state, None, iter(self.items())
|
| 292 |
+
|
| 293 |
+
def copy(self):
|
| 294 |
+
'od.copy() -> a shallow copy of od'
|
| 295 |
+
return self.__class__(self)
|
| 296 |
+
|
| 297 |
+
@classmethod
|
| 298 |
+
def fromkeys(cls, iterable, value=None):
|
| 299 |
+
'''Create a new ordered dictionary with keys from iterable and values set to value.
|
| 300 |
+
'''
|
| 301 |
+
self = cls()
|
| 302 |
+
for key in iterable:
|
| 303 |
+
self[key] = value
|
| 304 |
+
return self
|
| 305 |
+
|
| 306 |
+
def __eq__(self, other):
|
| 307 |
+
'''od.__eq__(y) <==> od==y. Comparison to another OD is order-sensitive
|
| 308 |
+
while comparison to a regular mapping is order-insensitive.
|
| 309 |
+
|
| 310 |
+
'''
|
| 311 |
+
if isinstance(other, OrderedDict):
|
| 312 |
+
return dict.__eq__(self, other) and all(map(_eq, self, other))
|
| 313 |
+
return dict.__eq__(self, other)
|
| 314 |
+
|
| 315 |
+
def __ior__(self, other):
|
| 316 |
+
self.update(other)
|
| 317 |
+
return self
|
| 318 |
+
|
| 319 |
+
def __or__(self, other):
|
| 320 |
+
if not isinstance(other, dict):
|
| 321 |
+
return NotImplemented
|
| 322 |
+
new = self.__class__(self)
|
| 323 |
+
new.update(other)
|
| 324 |
+
return new
|
| 325 |
+
|
| 326 |
+
def __ror__(self, other):
|
| 327 |
+
if not isinstance(other, dict):
|
| 328 |
+
return NotImplemented
|
| 329 |
+
new = self.__class__(other)
|
| 330 |
+
new.update(self)
|
| 331 |
+
return new
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
try:
|
| 335 |
+
from _collections import OrderedDict
|
| 336 |
+
except ImportError:
|
| 337 |
+
# Leave the pure Python version in place.
|
| 338 |
+
pass
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
################################################################################
|
| 342 |
+
### namedtuple
|
| 343 |
+
################################################################################
|
| 344 |
+
|
| 345 |
+
try:
|
| 346 |
+
from _collections import _tuplegetter
|
| 347 |
+
except ImportError:
|
| 348 |
+
_tuplegetter = lambda index, doc: property(_itemgetter(index), doc=doc)
|
| 349 |
+
|
| 350 |
+
def namedtuple(typename, field_names, *, rename=False, defaults=None, module=None):
|
| 351 |
+
"""Returns a new subclass of tuple with named fields.
|
| 352 |
+
|
| 353 |
+
>>> Point = namedtuple('Point', ['x', 'y'])
|
| 354 |
+
>>> Point.__doc__ # docstring for the new class
|
| 355 |
+
'Point(x, y)'
|
| 356 |
+
>>> p = Point(11, y=22) # instantiate with positional args or keywords
|
| 357 |
+
>>> p[0] + p[1] # indexable like a plain tuple
|
| 358 |
+
33
|
| 359 |
+
>>> x, y = p # unpack like a regular tuple
|
| 360 |
+
>>> x, y
|
| 361 |
+
(11, 22)
|
| 362 |
+
>>> p.x + p.y # fields also accessible by name
|
| 363 |
+
33
|
| 364 |
+
>>> d = p._asdict() # convert to a dictionary
|
| 365 |
+
>>> d['x']
|
| 366 |
+
11
|
| 367 |
+
>>> Point(**d) # convert from a dictionary
|
| 368 |
+
Point(x=11, y=22)
|
| 369 |
+
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
|
| 370 |
+
Point(x=100, y=22)
|
| 371 |
+
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
# Validate the field names. At the user's option, either generate an error
|
| 375 |
+
# message or automatically replace the field name with a valid name.
|
| 376 |
+
if isinstance(field_names, str):
|
| 377 |
+
field_names = field_names.replace(',', ' ').split()
|
| 378 |
+
field_names = list(map(str, field_names))
|
| 379 |
+
typename = _sys.intern(str(typename))
|
| 380 |
+
|
| 381 |
+
if rename:
|
| 382 |
+
seen = set()
|
| 383 |
+
for index, name in enumerate(field_names):
|
| 384 |
+
if (not name.isidentifier()
|
| 385 |
+
or _iskeyword(name)
|
| 386 |
+
or name.startswith('_')
|
| 387 |
+
or name in seen):
|
| 388 |
+
field_names[index] = f'_{index}'
|
| 389 |
+
seen.add(name)
|
| 390 |
+
|
| 391 |
+
for name in [typename] + field_names:
|
| 392 |
+
if type(name) is not str:
|
| 393 |
+
raise TypeError('Type names and field names must be strings')
|
| 394 |
+
if not name.isidentifier():
|
| 395 |
+
raise ValueError('Type names and field names must be valid '
|
| 396 |
+
f'identifiers: {name!r}')
|
| 397 |
+
if _iskeyword(name):
|
| 398 |
+
raise ValueError('Type names and field names cannot be a '
|
| 399 |
+
f'keyword: {name!r}')
|
| 400 |
+
|
| 401 |
+
seen = set()
|
| 402 |
+
for name in field_names:
|
| 403 |
+
if name.startswith('_') and not rename:
|
| 404 |
+
raise ValueError('Field names cannot start with an underscore: '
|
| 405 |
+
f'{name!r}')
|
| 406 |
+
if name in seen:
|
| 407 |
+
raise ValueError(f'Encountered duplicate field name: {name!r}')
|
| 408 |
+
seen.add(name)
|
| 409 |
+
|
| 410 |
+
field_defaults = {}
|
| 411 |
+
if defaults is not None:
|
| 412 |
+
defaults = tuple(defaults)
|
| 413 |
+
if len(defaults) > len(field_names):
|
| 414 |
+
raise TypeError('Got more default values than field names')
|
| 415 |
+
field_defaults = dict(reversed(list(zip(reversed(field_names),
|
| 416 |
+
reversed(defaults)))))
|
| 417 |
+
|
| 418 |
+
# Variables used in the methods and docstrings
|
| 419 |
+
field_names = tuple(map(_sys.intern, field_names))
|
| 420 |
+
num_fields = len(field_names)
|
| 421 |
+
arg_list = ', '.join(field_names)
|
| 422 |
+
if num_fields == 1:
|
| 423 |
+
arg_list += ','
|
| 424 |
+
repr_fmt = '(' + ', '.join(f'{name}=%r' for name in field_names) + ')'
|
| 425 |
+
tuple_new = tuple.__new__
|
| 426 |
+
_dict, _tuple, _len, _map, _zip = dict, tuple, len, map, zip
|
| 427 |
+
|
| 428 |
+
# Create all the named tuple methods to be added to the class namespace
|
| 429 |
+
|
| 430 |
+
namespace = {
|
| 431 |
+
'_tuple_new': tuple_new,
|
| 432 |
+
'__builtins__': {},
|
| 433 |
+
'__name__': f'namedtuple_{typename}',
|
| 434 |
+
}
|
| 435 |
+
code = f'lambda _cls, {arg_list}: _tuple_new(_cls, ({arg_list}))'
|
| 436 |
+
__new__ = eval(code, namespace)
|
| 437 |
+
__new__.__name__ = '__new__'
|
| 438 |
+
__new__.__doc__ = f'Create new instance of {typename}({arg_list})'
|
| 439 |
+
if defaults is not None:
|
| 440 |
+
__new__.__defaults__ = defaults
|
| 441 |
+
|
| 442 |
+
@classmethod
|
| 443 |
+
def _make(cls, iterable):
|
| 444 |
+
result = tuple_new(cls, iterable)
|
| 445 |
+
if _len(result) != num_fields:
|
| 446 |
+
raise TypeError(f'Expected {num_fields} arguments, got {len(result)}')
|
| 447 |
+
return result
|
| 448 |
+
|
| 449 |
+
_make.__func__.__doc__ = (f'Make a new {typename} object from a sequence '
|
| 450 |
+
'or iterable')
|
| 451 |
+
|
| 452 |
+
def _replace(self, /, **kwds):
|
| 453 |
+
result = self._make(_map(kwds.pop, field_names, self))
|
| 454 |
+
if kwds:
|
| 455 |
+
raise ValueError(f'Got unexpected field names: {list(kwds)!r}')
|
| 456 |
+
return result
|
| 457 |
+
|
| 458 |
+
_replace.__doc__ = (f'Return a new {typename} object replacing specified '
|
| 459 |
+
'fields with new values')
|
| 460 |
+
|
| 461 |
+
def __repr__(self):
|
| 462 |
+
'Return a nicely formatted representation string'
|
| 463 |
+
return self.__class__.__name__ + repr_fmt % self
|
| 464 |
+
|
| 465 |
+
def _asdict(self):
|
| 466 |
+
'Return a new dict which maps field names to their values.'
|
| 467 |
+
return _dict(_zip(self._fields, self))
|
| 468 |
+
|
| 469 |
+
def __getnewargs__(self):
|
| 470 |
+
'Return self as a plain tuple. Used by copy and pickle.'
|
| 471 |
+
return _tuple(self)
|
| 472 |
+
|
| 473 |
+
# Modify function metadata to help with introspection and debugging
|
| 474 |
+
for method in (
|
| 475 |
+
__new__,
|
| 476 |
+
_make.__func__,
|
| 477 |
+
_replace,
|
| 478 |
+
__repr__,
|
| 479 |
+
_asdict,
|
| 480 |
+
__getnewargs__,
|
| 481 |
+
):
|
| 482 |
+
method.__qualname__ = f'{typename}.{method.__name__}'
|
| 483 |
+
|
| 484 |
+
# Build-up the class namespace dictionary
|
| 485 |
+
# and use type() to build the result class
|
| 486 |
+
class_namespace = {
|
| 487 |
+
'__doc__': f'{typename}({arg_list})',
|
| 488 |
+
'__slots__': (),
|
| 489 |
+
'_fields': field_names,
|
| 490 |
+
'_field_defaults': field_defaults,
|
| 491 |
+
'__new__': __new__,
|
| 492 |
+
'_make': _make,
|
| 493 |
+
'_replace': _replace,
|
| 494 |
+
'__repr__': __repr__,
|
| 495 |
+
'_asdict': _asdict,
|
| 496 |
+
'__getnewargs__': __getnewargs__,
|
| 497 |
+
'__match_args__': field_names,
|
| 498 |
+
}
|
| 499 |
+
for index, name in enumerate(field_names):
|
| 500 |
+
doc = _sys.intern(f'Alias for field number {index}')
|
| 501 |
+
class_namespace[name] = _tuplegetter(index, doc)
|
| 502 |
+
|
| 503 |
+
result = type(typename, (tuple,), class_namespace)
|
| 504 |
+
|
| 505 |
+
# For pickling to work, the __module__ variable needs to be set to the frame
|
| 506 |
+
# where the named tuple is created. Bypass this step in environments where
|
| 507 |
+
# sys._getframe is not defined (Jython for example) or sys._getframe is not
|
| 508 |
+
# defined for arguments greater than 0 (IronPython), or where the user has
|
| 509 |
+
# specified a particular module.
|
| 510 |
+
if module is None:
|
| 511 |
+
try:
|
| 512 |
+
module = _sys._getframe(1).f_globals.get('__name__', '__main__')
|
| 513 |
+
except (AttributeError, ValueError):
|
| 514 |
+
pass
|
| 515 |
+
if module is not None:
|
| 516 |
+
result.__module__ = module
|
| 517 |
+
|
| 518 |
+
return result
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
########################################################################
|
| 522 |
+
### Counter
|
| 523 |
+
########################################################################
|
| 524 |
+
|
| 525 |
+
def _count_elements(mapping, iterable):
|
| 526 |
+
'Tally elements from the iterable.'
|
| 527 |
+
mapping_get = mapping.get
|
| 528 |
+
for elem in iterable:
|
| 529 |
+
mapping[elem] = mapping_get(elem, 0) + 1
|
| 530 |
+
|
| 531 |
+
try: # Load C helper function if available
|
| 532 |
+
from _collections import _count_elements
|
| 533 |
+
except ImportError:
|
| 534 |
+
pass
|
| 535 |
+
|
| 536 |
+
class Counter(dict):
|
| 537 |
+
'''Dict subclass for counting hashable items. Sometimes called a bag
|
| 538 |
+
or multiset. Elements are stored as dictionary keys and their counts
|
| 539 |
+
are stored as dictionary values.
|
| 540 |
+
|
| 541 |
+
>>> c = Counter('abcdeabcdabcaba') # count elements from a string
|
| 542 |
+
|
| 543 |
+
>>> c.most_common(3) # three most common elements
|
| 544 |
+
[('a', 5), ('b', 4), ('c', 3)]
|
| 545 |
+
>>> sorted(c) # list all unique elements
|
| 546 |
+
['a', 'b', 'c', 'd', 'e']
|
| 547 |
+
>>> ''.join(sorted(c.elements())) # list elements with repetitions
|
| 548 |
+
'aaaaabbbbcccdde'
|
| 549 |
+
>>> sum(c.values()) # total of all counts
|
| 550 |
+
15
|
| 551 |
+
|
| 552 |
+
>>> c['a'] # count of letter 'a'
|
| 553 |
+
5
|
| 554 |
+
>>> for elem in 'shazam': # update counts from an iterable
|
| 555 |
+
... c[elem] += 1 # by adding 1 to each element's count
|
| 556 |
+
>>> c['a'] # now there are seven 'a'
|
| 557 |
+
7
|
| 558 |
+
>>> del c['b'] # remove all 'b'
|
| 559 |
+
>>> c['b'] # now there are zero 'b'
|
| 560 |
+
0
|
| 561 |
+
|
| 562 |
+
>>> d = Counter('simsalabim') # make another counter
|
| 563 |
+
>>> c.update(d) # add in the second counter
|
| 564 |
+
>>> c['a'] # now there are nine 'a'
|
| 565 |
+
9
|
| 566 |
+
|
| 567 |
+
>>> c.clear() # empty the counter
|
| 568 |
+
>>> c
|
| 569 |
+
Counter()
|
| 570 |
+
|
| 571 |
+
Note: If a count is set to zero or reduced to zero, it will remain
|
| 572 |
+
in the counter until the entry is deleted or the counter is cleared:
|
| 573 |
+
|
| 574 |
+
>>> c = Counter('aaabbc')
|
| 575 |
+
>>> c['b'] -= 2 # reduce the count of 'b' by two
|
| 576 |
+
>>> c.most_common() # 'b' is still in, but its count is zero
|
| 577 |
+
[('a', 3), ('c', 1), ('b', 0)]
|
| 578 |
+
|
| 579 |
+
'''
|
| 580 |
+
# References:
|
| 581 |
+
# http://en.wikipedia.org/wiki/Multiset
|
| 582 |
+
# http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
|
| 583 |
+
# http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
|
| 584 |
+
# http://code.activestate.com/recipes/259174/
|
| 585 |
+
# Knuth, TAOCP Vol. II section 4.6.3
|
| 586 |
+
|
| 587 |
+
def __init__(self, iterable=None, /, **kwds):
|
| 588 |
+
'''Create a new, empty Counter object. And if given, count elements
|
| 589 |
+
from an input iterable. Or, initialize the count from another mapping
|
| 590 |
+
of elements to their counts.
|
| 591 |
+
|
| 592 |
+
>>> c = Counter() # a new, empty counter
|
| 593 |
+
>>> c = Counter('gallahad') # a new counter from an iterable
|
| 594 |
+
>>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
|
| 595 |
+
>>> c = Counter(a=4, b=2) # a new counter from keyword args
|
| 596 |
+
|
| 597 |
+
'''
|
| 598 |
+
super().__init__()
|
| 599 |
+
self.update(iterable, **kwds)
|
| 600 |
+
|
| 601 |
+
def __missing__(self, key):
|
| 602 |
+
'The count of elements not in the Counter is zero.'
|
| 603 |
+
# Needed so that self[missing_item] does not raise KeyError
|
| 604 |
+
return 0
|
| 605 |
+
|
| 606 |
+
def total(self):
|
| 607 |
+
'Sum of the counts'
|
| 608 |
+
return sum(self.values())
|
| 609 |
+
|
| 610 |
+
def most_common(self, n=None):
|
| 611 |
+
'''List the n most common elements and their counts from the most
|
| 612 |
+
common to the least. If n is None, then list all element counts.
|
| 613 |
+
|
| 614 |
+
>>> Counter('abracadabra').most_common(3)
|
| 615 |
+
[('a', 5), ('b', 2), ('r', 2)]
|
| 616 |
+
|
| 617 |
+
'''
|
| 618 |
+
# Emulate Bag.sortedByCount from Smalltalk
|
| 619 |
+
if n is None:
|
| 620 |
+
return sorted(self.items(), key=_itemgetter(1), reverse=True)
|
| 621 |
+
|
| 622 |
+
# Lazy import to speedup Python startup time
|
| 623 |
+
import heapq
|
| 624 |
+
return heapq.nlargest(n, self.items(), key=_itemgetter(1))
|
| 625 |
+
|
| 626 |
+
def elements(self):
|
| 627 |
+
'''Iterator over elements repeating each as many times as its count.
|
| 628 |
+
|
| 629 |
+
>>> c = Counter('ABCABC')
|
| 630 |
+
>>> sorted(c.elements())
|
| 631 |
+
['A', 'A', 'B', 'B', 'C', 'C']
|
| 632 |
+
|
| 633 |
+
# Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
|
| 634 |
+
>>> import math
|
| 635 |
+
>>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
|
| 636 |
+
>>> math.prod(prime_factors.elements())
|
| 637 |
+
1836
|
| 638 |
+
|
| 639 |
+
Note, if an element's count has been set to zero or is a negative
|
| 640 |
+
number, elements() will ignore it.
|
| 641 |
+
|
| 642 |
+
'''
|
| 643 |
+
# Emulate Bag.do from Smalltalk and Multiset.begin from C++.
|
| 644 |
+
return _chain.from_iterable(_starmap(_repeat, self.items()))
|
| 645 |
+
|
| 646 |
+
# Override dict methods where necessary
|
| 647 |
+
|
| 648 |
+
@classmethod
|
| 649 |
+
def fromkeys(cls, iterable, v=None):
|
| 650 |
+
# There is no equivalent method for counters because the semantics
|
| 651 |
+
# would be ambiguous in cases such as Counter.fromkeys('aaabbc', v=2).
|
| 652 |
+
# Initializing counters to zero values isn't necessary because zero
|
| 653 |
+
# is already the default value for counter lookups. Initializing
|
| 654 |
+
# to one is easily accomplished with Counter(set(iterable)). For
|
| 655 |
+
# more exotic cases, create a dictionary first using a dictionary
|
| 656 |
+
# comprehension or dict.fromkeys().
|
| 657 |
+
raise NotImplementedError(
|
| 658 |
+
'Counter.fromkeys() is undefined. Use Counter(iterable) instead.')
|
| 659 |
+
|
| 660 |
+
def update(self, iterable=None, /, **kwds):
|
| 661 |
+
'''Like dict.update() but add counts instead of replacing them.
|
| 662 |
+
|
| 663 |
+
Source can be an iterable, a dictionary, or another Counter instance.
|
| 664 |
+
|
| 665 |
+
>>> c = Counter('which')
|
| 666 |
+
>>> c.update('witch') # add elements from another iterable
|
| 667 |
+
>>> d = Counter('watch')
|
| 668 |
+
>>> c.update(d) # add elements from another counter
|
| 669 |
+
>>> c['h'] # four 'h' in which, witch, and watch
|
| 670 |
+
4
|
| 671 |
+
|
| 672 |
+
'''
|
| 673 |
+
# The regular dict.update() operation makes no sense here because the
|
| 674 |
+
# replace behavior results in some of the original untouched counts
|
| 675 |
+
# being mixed-in with all of the other counts for a mismash that
|
| 676 |
+
# doesn't have a straight-forward interpretation in most counting
|
| 677 |
+
# contexts. Instead, we implement straight-addition. Both the inputs
|
| 678 |
+
# and outputs are allowed to contain zero and negative counts.
|
| 679 |
+
|
| 680 |
+
if iterable is not None:
|
| 681 |
+
if isinstance(iterable, _collections_abc.Mapping):
|
| 682 |
+
if self:
|
| 683 |
+
self_get = self.get
|
| 684 |
+
for elem, count in iterable.items():
|
| 685 |
+
self[elem] = count + self_get(elem, 0)
|
| 686 |
+
else:
|
| 687 |
+
# fast path when counter is empty
|
| 688 |
+
super().update(iterable)
|
| 689 |
+
else:
|
| 690 |
+
_count_elements(self, iterable)
|
| 691 |
+
if kwds:
|
| 692 |
+
self.update(kwds)
|
| 693 |
+
|
| 694 |
+
def subtract(self, iterable=None, /, **kwds):
|
| 695 |
+
'''Like dict.update() but subtracts counts instead of replacing them.
|
| 696 |
+
Counts can be reduced below zero. Both the inputs and outputs are
|
| 697 |
+
allowed to contain zero and negative counts.
|
| 698 |
+
|
| 699 |
+
Source can be an iterable, a dictionary, or another Counter instance.
|
| 700 |
+
|
| 701 |
+
>>> c = Counter('which')
|
| 702 |
+
>>> c.subtract('witch') # subtract elements from another iterable
|
| 703 |
+
>>> c.subtract(Counter('watch')) # subtract elements from another counter
|
| 704 |
+
>>> c['h'] # 2 in which, minus 1 in witch, minus 1 in watch
|
| 705 |
+
0
|
| 706 |
+
>>> c['w'] # 1 in which, minus 1 in witch, minus 1 in watch
|
| 707 |
+
-1
|
| 708 |
+
|
| 709 |
+
'''
|
| 710 |
+
if iterable is not None:
|
| 711 |
+
self_get = self.get
|
| 712 |
+
if isinstance(iterable, _collections_abc.Mapping):
|
| 713 |
+
for elem, count in iterable.items():
|
| 714 |
+
self[elem] = self_get(elem, 0) - count
|
| 715 |
+
else:
|
| 716 |
+
for elem in iterable:
|
| 717 |
+
self[elem] = self_get(elem, 0) - 1
|
| 718 |
+
if kwds:
|
| 719 |
+
self.subtract(kwds)
|
| 720 |
+
|
| 721 |
+
def copy(self):
|
| 722 |
+
'Return a shallow copy.'
|
| 723 |
+
return self.__class__(self)
|
| 724 |
+
|
| 725 |
+
def __reduce__(self):
|
| 726 |
+
return self.__class__, (dict(self),)
|
| 727 |
+
|
| 728 |
+
def __delitem__(self, elem):
|
| 729 |
+
'Like dict.__delitem__() but does not raise KeyError for missing values.'
|
| 730 |
+
if elem in self:
|
| 731 |
+
super().__delitem__(elem)
|
| 732 |
+
|
| 733 |
+
def __repr__(self):
|
| 734 |
+
if not self:
|
| 735 |
+
return f'{self.__class__.__name__}()'
|
| 736 |
+
try:
|
| 737 |
+
# dict() preserves the ordering returned by most_common()
|
| 738 |
+
d = dict(self.most_common())
|
| 739 |
+
except TypeError:
|
| 740 |
+
# handle case where values are not orderable
|
| 741 |
+
d = dict(self)
|
| 742 |
+
return f'{self.__class__.__name__}({d!r})'
|
| 743 |
+
|
| 744 |
+
# Multiset-style mathematical operations discussed in:
|
| 745 |
+
# Knuth TAOCP Volume II section 4.6.3 exercise 19
|
| 746 |
+
# and at http://en.wikipedia.org/wiki/Multiset
|
| 747 |
+
#
|
| 748 |
+
# Outputs guaranteed to only include positive counts.
|
| 749 |
+
#
|
| 750 |
+
# To strip negative and zero counts, add-in an empty counter:
|
| 751 |
+
# c += Counter()
|
| 752 |
+
#
|
| 753 |
+
# Results are ordered according to when an element is first
|
| 754 |
+
# encountered in the left operand and then by the order
|
| 755 |
+
# encountered in the right operand.
|
| 756 |
+
#
|
| 757 |
+
# When the multiplicities are all zero or one, multiset operations
|
| 758 |
+
# are guaranteed to be equivalent to the corresponding operations
|
| 759 |
+
# for regular sets.
|
| 760 |
+
# Given counter multisets such as:
|
| 761 |
+
# cp = Counter(a=1, b=0, c=1)
|
| 762 |
+
# cq = Counter(c=1, d=0, e=1)
|
| 763 |
+
# The corresponding regular sets would be:
|
| 764 |
+
# sp = {'a', 'c'}
|
| 765 |
+
# sq = {'c', 'e'}
|
| 766 |
+
# All of the following relations would hold:
|
| 767 |
+
# set(cp + cq) == sp | sq
|
| 768 |
+
# set(cp - cq) == sp - sq
|
| 769 |
+
# set(cp | cq) == sp | sq
|
| 770 |
+
# set(cp & cq) == sp & sq
|
| 771 |
+
# (cp == cq) == (sp == sq)
|
| 772 |
+
# (cp != cq) == (sp != sq)
|
| 773 |
+
# (cp <= cq) == (sp <= sq)
|
| 774 |
+
# (cp < cq) == (sp < sq)
|
| 775 |
+
# (cp >= cq) == (sp >= sq)
|
| 776 |
+
# (cp > cq) == (sp > sq)
|
| 777 |
+
|
| 778 |
+
def __eq__(self, other):
|
| 779 |
+
'True if all counts agree. Missing counts are treated as zero.'
|
| 780 |
+
if not isinstance(other, Counter):
|
| 781 |
+
return NotImplemented
|
| 782 |
+
return all(self[e] == other[e] for c in (self, other) for e in c)
|
| 783 |
+
|
| 784 |
+
def __ne__(self, other):
|
| 785 |
+
'True if any counts disagree. Missing counts are treated as zero.'
|
| 786 |
+
if not isinstance(other, Counter):
|
| 787 |
+
return NotImplemented
|
| 788 |
+
return not self == other
|
| 789 |
+
|
| 790 |
+
def __le__(self, other):
|
| 791 |
+
'True if all counts in self are a subset of those in other.'
|
| 792 |
+
if not isinstance(other, Counter):
|
| 793 |
+
return NotImplemented
|
| 794 |
+
return all(self[e] <= other[e] for c in (self, other) for e in c)
|
| 795 |
+
|
| 796 |
+
def __lt__(self, other):
|
| 797 |
+
'True if all counts in self are a proper subset of those in other.'
|
| 798 |
+
if not isinstance(other, Counter):
|
| 799 |
+
return NotImplemented
|
| 800 |
+
return self <= other and self != other
|
| 801 |
+
|
| 802 |
+
def __ge__(self, other):
|
| 803 |
+
'True if all counts in self are a superset of those in other.'
|
| 804 |
+
if not isinstance(other, Counter):
|
| 805 |
+
return NotImplemented
|
| 806 |
+
return all(self[e] >= other[e] for c in (self, other) for e in c)
|
| 807 |
+
|
| 808 |
+
def __gt__(self, other):
|
| 809 |
+
'True if all counts in self are a proper superset of those in other.'
|
| 810 |
+
if not isinstance(other, Counter):
|
| 811 |
+
return NotImplemented
|
| 812 |
+
return self >= other and self != other
|
| 813 |
+
|
| 814 |
+
def __add__(self, other):
|
| 815 |
+
'''Add counts from two counters.
|
| 816 |
+
|
| 817 |
+
>>> Counter('abbb') + Counter('bcc')
|
| 818 |
+
Counter({'b': 4, 'c': 2, 'a': 1})
|
| 819 |
+
|
| 820 |
+
'''
|
| 821 |
+
if not isinstance(other, Counter):
|
| 822 |
+
return NotImplemented
|
| 823 |
+
result = Counter()
|
| 824 |
+
for elem, count in self.items():
|
| 825 |
+
newcount = count + other[elem]
|
| 826 |
+
if newcount > 0:
|
| 827 |
+
result[elem] = newcount
|
| 828 |
+
for elem, count in other.items():
|
| 829 |
+
if elem not in self and count > 0:
|
| 830 |
+
result[elem] = count
|
| 831 |
+
return result
|
| 832 |
+
|
| 833 |
+
def __sub__(self, other):
|
| 834 |
+
''' Subtract count, but keep only results with positive counts.
|
| 835 |
+
|
| 836 |
+
>>> Counter('abbbc') - Counter('bccd')
|
| 837 |
+
Counter({'b': 2, 'a': 1})
|
| 838 |
+
|
| 839 |
+
'''
|
| 840 |
+
if not isinstance(other, Counter):
|
| 841 |
+
return NotImplemented
|
| 842 |
+
result = Counter()
|
| 843 |
+
for elem, count in self.items():
|
| 844 |
+
newcount = count - other[elem]
|
| 845 |
+
if newcount > 0:
|
| 846 |
+
result[elem] = newcount
|
| 847 |
+
for elem, count in other.items():
|
| 848 |
+
if elem not in self and count < 0:
|
| 849 |
+
result[elem] = 0 - count
|
| 850 |
+
return result
|
| 851 |
+
|
| 852 |
+
def __or__(self, other):
|
| 853 |
+
'''Union is the maximum of value in either of the input counters.
|
| 854 |
+
|
| 855 |
+
>>> Counter('abbb') | Counter('bcc')
|
| 856 |
+
Counter({'b': 3, 'c': 2, 'a': 1})
|
| 857 |
+
|
| 858 |
+
'''
|
| 859 |
+
if not isinstance(other, Counter):
|
| 860 |
+
return NotImplemented
|
| 861 |
+
result = Counter()
|
| 862 |
+
for elem, count in self.items():
|
| 863 |
+
other_count = other[elem]
|
| 864 |
+
newcount = other_count if count < other_count else count
|
| 865 |
+
if newcount > 0:
|
| 866 |
+
result[elem] = newcount
|
| 867 |
+
for elem, count in other.items():
|
| 868 |
+
if elem not in self and count > 0:
|
| 869 |
+
result[elem] = count
|
| 870 |
+
return result
|
| 871 |
+
|
| 872 |
+
def __and__(self, other):
|
| 873 |
+
''' Intersection is the minimum of corresponding counts.
|
| 874 |
+
|
| 875 |
+
>>> Counter('abbb') & Counter('bcc')
|
| 876 |
+
Counter({'b': 1})
|
| 877 |
+
|
| 878 |
+
'''
|
| 879 |
+
if not isinstance(other, Counter):
|
| 880 |
+
return NotImplemented
|
| 881 |
+
result = Counter()
|
| 882 |
+
for elem, count in self.items():
|
| 883 |
+
other_count = other[elem]
|
| 884 |
+
newcount = count if count < other_count else other_count
|
| 885 |
+
if newcount > 0:
|
| 886 |
+
result[elem] = newcount
|
| 887 |
+
return result
|
| 888 |
+
|
| 889 |
+
def __pos__(self):
|
| 890 |
+
'Adds an empty counter, effectively stripping negative and zero counts'
|
| 891 |
+
result = Counter()
|
| 892 |
+
for elem, count in self.items():
|
| 893 |
+
if count > 0:
|
| 894 |
+
result[elem] = count
|
| 895 |
+
return result
|
| 896 |
+
|
| 897 |
+
def __neg__(self):
|
| 898 |
+
'''Subtracts from an empty counter. Strips positive and zero counts,
|
| 899 |
+
and flips the sign on negative counts.
|
| 900 |
+
|
| 901 |
+
'''
|
| 902 |
+
result = Counter()
|
| 903 |
+
for elem, count in self.items():
|
| 904 |
+
if count < 0:
|
| 905 |
+
result[elem] = 0 - count
|
| 906 |
+
return result
|
| 907 |
+
|
| 908 |
+
def _keep_positive(self):
|
| 909 |
+
'''Internal method to strip elements with a negative or zero count'''
|
| 910 |
+
nonpositive = [elem for elem, count in self.items() if not count > 0]
|
| 911 |
+
for elem in nonpositive:
|
| 912 |
+
del self[elem]
|
| 913 |
+
return self
|
| 914 |
+
|
| 915 |
+
def __iadd__(self, other):
|
| 916 |
+
'''Inplace add from another counter, keeping only positive counts.
|
| 917 |
+
|
| 918 |
+
>>> c = Counter('abbb')
|
| 919 |
+
>>> c += Counter('bcc')
|
| 920 |
+
>>> c
|
| 921 |
+
Counter({'b': 4, 'c': 2, 'a': 1})
|
| 922 |
+
|
| 923 |
+
'''
|
| 924 |
+
for elem, count in other.items():
|
| 925 |
+
self[elem] += count
|
| 926 |
+
return self._keep_positive()
|
| 927 |
+
|
| 928 |
+
def __isub__(self, other):
|
| 929 |
+
'''Inplace subtract counter, but keep only results with positive counts.
|
| 930 |
+
|
| 931 |
+
>>> c = Counter('abbbc')
|
| 932 |
+
>>> c -= Counter('bccd')
|
| 933 |
+
>>> c
|
| 934 |
+
Counter({'b': 2, 'a': 1})
|
| 935 |
+
|
| 936 |
+
'''
|
| 937 |
+
for elem, count in other.items():
|
| 938 |
+
self[elem] -= count
|
| 939 |
+
return self._keep_positive()
|
| 940 |
+
|
| 941 |
+
def __ior__(self, other):
|
| 942 |
+
'''Inplace union is the maximum of value from either counter.
|
| 943 |
+
|
| 944 |
+
>>> c = Counter('abbb')
|
| 945 |
+
>>> c |= Counter('bcc')
|
| 946 |
+
>>> c
|
| 947 |
+
Counter({'b': 3, 'c': 2, 'a': 1})
|
| 948 |
+
|
| 949 |
+
'''
|
| 950 |
+
for elem, other_count in other.items():
|
| 951 |
+
count = self[elem]
|
| 952 |
+
if other_count > count:
|
| 953 |
+
self[elem] = other_count
|
| 954 |
+
return self._keep_positive()
|
| 955 |
+
|
| 956 |
+
def __iand__(self, other):
|
| 957 |
+
'''Inplace intersection is the minimum of corresponding counts.
|
| 958 |
+
|
| 959 |
+
>>> c = Counter('abbb')
|
| 960 |
+
>>> c &= Counter('bcc')
|
| 961 |
+
>>> c
|
| 962 |
+
Counter({'b': 1})
|
| 963 |
+
|
| 964 |
+
'''
|
| 965 |
+
for elem, count in self.items():
|
| 966 |
+
other_count = other[elem]
|
| 967 |
+
if other_count < count:
|
| 968 |
+
self[elem] = other_count
|
| 969 |
+
return self._keep_positive()
|
| 970 |
+
|
| 971 |
+
|
| 972 |
+
########################################################################
|
| 973 |
+
### ChainMap
|
| 974 |
+
########################################################################
|
| 975 |
+
|
| 976 |
+
class ChainMap(_collections_abc.MutableMapping):
|
| 977 |
+
''' A ChainMap groups multiple dicts (or other mappings) together
|
| 978 |
+
to create a single, updateable view.
|
| 979 |
+
|
| 980 |
+
The underlying mappings are stored in a list. That list is public and can
|
| 981 |
+
be accessed or updated using the *maps* attribute. There is no other
|
| 982 |
+
state.
|
| 983 |
+
|
| 984 |
+
Lookups search the underlying mappings successively until a key is found.
|
| 985 |
+
In contrast, writes, updates, and deletions only operate on the first
|
| 986 |
+
mapping.
|
| 987 |
+
|
| 988 |
+
'''
|
| 989 |
+
|
| 990 |
+
def __init__(self, *maps):
|
| 991 |
+
'''Initialize a ChainMap by setting *maps* to the given mappings.
|
| 992 |
+
If no mappings are provided, a single empty dictionary is used.
|
| 993 |
+
|
| 994 |
+
'''
|
| 995 |
+
self.maps = list(maps) or [{}] # always at least one map
|
| 996 |
+
|
| 997 |
+
def __missing__(self, key):
|
| 998 |
+
raise KeyError(key)
|
| 999 |
+
|
| 1000 |
+
def __getitem__(self, key):
|
| 1001 |
+
for mapping in self.maps:
|
| 1002 |
+
try:
|
| 1003 |
+
return mapping[key] # can't use 'key in mapping' with defaultdict
|
| 1004 |
+
except KeyError:
|
| 1005 |
+
pass
|
| 1006 |
+
return self.__missing__(key) # support subclasses that define __missing__
|
| 1007 |
+
|
| 1008 |
+
def get(self, key, default=None):
|
| 1009 |
+
return self[key] if key in self else default
|
| 1010 |
+
|
| 1011 |
+
def __len__(self):
|
| 1012 |
+
return len(set().union(*self.maps)) # reuses stored hash values if possible
|
| 1013 |
+
|
| 1014 |
+
def __iter__(self):
|
| 1015 |
+
d = {}
|
| 1016 |
+
for mapping in reversed(self.maps):
|
| 1017 |
+
d.update(dict.fromkeys(mapping)) # reuses stored hash values if possible
|
| 1018 |
+
return iter(d)
|
| 1019 |
+
|
| 1020 |
+
def __contains__(self, key):
|
| 1021 |
+
return any(key in m for m in self.maps)
|
| 1022 |
+
|
| 1023 |
+
def __bool__(self):
|
| 1024 |
+
return any(self.maps)
|
| 1025 |
+
|
| 1026 |
+
@_recursive_repr()
|
| 1027 |
+
def __repr__(self):
|
| 1028 |
+
return f'{self.__class__.__name__}({", ".join(map(repr, self.maps))})'
|
| 1029 |
+
|
| 1030 |
+
@classmethod
|
| 1031 |
+
def fromkeys(cls, iterable, *args):
|
| 1032 |
+
'Create a ChainMap with a single dict created from the iterable.'
|
| 1033 |
+
return cls(dict.fromkeys(iterable, *args))
|
| 1034 |
+
|
| 1035 |
+
def copy(self):
|
| 1036 |
+
'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'
|
| 1037 |
+
return self.__class__(self.maps[0].copy(), *self.maps[1:])
|
| 1038 |
+
|
| 1039 |
+
__copy__ = copy
|
| 1040 |
+
|
| 1041 |
+
def new_child(self, m=None, **kwargs): # like Django's Context.push()
|
| 1042 |
+
'''New ChainMap with a new map followed by all previous maps.
|
| 1043 |
+
If no map is provided, an empty dict is used.
|
| 1044 |
+
Keyword arguments update the map or new empty dict.
|
| 1045 |
+
'''
|
| 1046 |
+
if m is None:
|
| 1047 |
+
m = kwargs
|
| 1048 |
+
elif kwargs:
|
| 1049 |
+
m.update(kwargs)
|
| 1050 |
+
return self.__class__(m, *self.maps)
|
| 1051 |
+
|
| 1052 |
+
@property
|
| 1053 |
+
def parents(self): # like Django's Context.pop()
|
| 1054 |
+
'New ChainMap from maps[1:].'
|
| 1055 |
+
return self.__class__(*self.maps[1:])
|
| 1056 |
+
|
| 1057 |
+
def __setitem__(self, key, value):
|
| 1058 |
+
self.maps[0][key] = value
|
| 1059 |
+
|
| 1060 |
+
def __delitem__(self, key):
|
| 1061 |
+
try:
|
| 1062 |
+
del self.maps[0][key]
|
| 1063 |
+
except KeyError:
|
| 1064 |
+
raise KeyError(f'Key not found in the first mapping: {key!r}')
|
| 1065 |
+
|
| 1066 |
+
def popitem(self):
|
| 1067 |
+
'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'
|
| 1068 |
+
try:
|
| 1069 |
+
return self.maps[0].popitem()
|
| 1070 |
+
except KeyError:
|
| 1071 |
+
raise KeyError('No keys found in the first mapping.')
|
| 1072 |
+
|
| 1073 |
+
def pop(self, key, *args):
|
| 1074 |
+
'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'
|
| 1075 |
+
try:
|
| 1076 |
+
return self.maps[0].pop(key, *args)
|
| 1077 |
+
except KeyError:
|
| 1078 |
+
raise KeyError(f'Key not found in the first mapping: {key!r}')
|
| 1079 |
+
|
| 1080 |
+
def clear(self):
|
| 1081 |
+
'Clear maps[0], leaving maps[1:] intact.'
|
| 1082 |
+
self.maps[0].clear()
|
| 1083 |
+
|
| 1084 |
+
def __ior__(self, other):
|
| 1085 |
+
self.maps[0].update(other)
|
| 1086 |
+
return self
|
| 1087 |
+
|
| 1088 |
+
def __or__(self, other):
|
| 1089 |
+
if not isinstance(other, _collections_abc.Mapping):
|
| 1090 |
+
return NotImplemented
|
| 1091 |
+
m = self.copy()
|
| 1092 |
+
m.maps[0].update(other)
|
| 1093 |
+
return m
|
| 1094 |
+
|
| 1095 |
+
def __ror__(self, other):
|
| 1096 |
+
if not isinstance(other, _collections_abc.Mapping):
|
| 1097 |
+
return NotImplemented
|
| 1098 |
+
m = dict(other)
|
| 1099 |
+
for child in reversed(self.maps):
|
| 1100 |
+
m.update(child)
|
| 1101 |
+
return self.__class__(m)
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
################################################################################
|
| 1105 |
+
### UserDict
|
| 1106 |
+
################################################################################
|
| 1107 |
+
|
| 1108 |
+
class UserDict(_collections_abc.MutableMapping):
|
| 1109 |
+
|
| 1110 |
+
# Start by filling-out the abstract methods
|
| 1111 |
+
def __init__(self, dict=None, /, **kwargs):
|
| 1112 |
+
self.data = {}
|
| 1113 |
+
if dict is not None:
|
| 1114 |
+
self.update(dict)
|
| 1115 |
+
if kwargs:
|
| 1116 |
+
self.update(kwargs)
|
| 1117 |
+
|
| 1118 |
+
def __len__(self):
|
| 1119 |
+
return len(self.data)
|
| 1120 |
+
|
| 1121 |
+
def __getitem__(self, key):
|
| 1122 |
+
if key in self.data:
|
| 1123 |
+
return self.data[key]
|
| 1124 |
+
if hasattr(self.__class__, "__missing__"):
|
| 1125 |
+
return self.__class__.__missing__(self, key)
|
| 1126 |
+
raise KeyError(key)
|
| 1127 |
+
|
| 1128 |
+
def __setitem__(self, key, item):
|
| 1129 |
+
self.data[key] = item
|
| 1130 |
+
|
| 1131 |
+
def __delitem__(self, key):
|
| 1132 |
+
del self.data[key]
|
| 1133 |
+
|
| 1134 |
+
def __iter__(self):
|
| 1135 |
+
return iter(self.data)
|
| 1136 |
+
|
| 1137 |
+
# Modify __contains__ to work correctly when __missing__ is present
|
| 1138 |
+
def __contains__(self, key):
|
| 1139 |
+
return key in self.data
|
| 1140 |
+
|
| 1141 |
+
# Now, add the methods in dicts but not in MutableMapping
|
| 1142 |
+
def __repr__(self):
|
| 1143 |
+
return repr(self.data)
|
| 1144 |
+
|
| 1145 |
+
def __or__(self, other):
|
| 1146 |
+
if isinstance(other, UserDict):
|
| 1147 |
+
return self.__class__(self.data | other.data)
|
| 1148 |
+
if isinstance(other, dict):
|
| 1149 |
+
return self.__class__(self.data | other)
|
| 1150 |
+
return NotImplemented
|
| 1151 |
+
|
| 1152 |
+
def __ror__(self, other):
|
| 1153 |
+
if isinstance(other, UserDict):
|
| 1154 |
+
return self.__class__(other.data | self.data)
|
| 1155 |
+
if isinstance(other, dict):
|
| 1156 |
+
return self.__class__(other | self.data)
|
| 1157 |
+
return NotImplemented
|
| 1158 |
+
|
| 1159 |
+
def __ior__(self, other):
|
| 1160 |
+
if isinstance(other, UserDict):
|
| 1161 |
+
self.data |= other.data
|
| 1162 |
+
else:
|
| 1163 |
+
self.data |= other
|
| 1164 |
+
return self
|
| 1165 |
+
|
| 1166 |
+
def __copy__(self):
|
| 1167 |
+
inst = self.__class__.__new__(self.__class__)
|
| 1168 |
+
inst.__dict__.update(self.__dict__)
|
| 1169 |
+
# Create a copy and avoid triggering descriptors
|
| 1170 |
+
inst.__dict__["data"] = self.__dict__["data"].copy()
|
| 1171 |
+
return inst
|
| 1172 |
+
|
| 1173 |
+
def copy(self):
|
| 1174 |
+
if self.__class__ is UserDict:
|
| 1175 |
+
return UserDict(self.data.copy())
|
| 1176 |
+
import copy
|
| 1177 |
+
data = self.data
|
| 1178 |
+
try:
|
| 1179 |
+
self.data = {}
|
| 1180 |
+
c = copy.copy(self)
|
| 1181 |
+
finally:
|
| 1182 |
+
self.data = data
|
| 1183 |
+
c.update(self)
|
| 1184 |
+
return c
|
| 1185 |
+
|
| 1186 |
+
@classmethod
|
| 1187 |
+
def fromkeys(cls, iterable, value=None):
|
| 1188 |
+
d = cls()
|
| 1189 |
+
for key in iterable:
|
| 1190 |
+
d[key] = value
|
| 1191 |
+
return d
|
| 1192 |
+
|
| 1193 |
+
|
| 1194 |
+
################################################################################
|
| 1195 |
+
### UserList
|
| 1196 |
+
################################################################################
|
| 1197 |
+
|
| 1198 |
+
class UserList(_collections_abc.MutableSequence):
|
| 1199 |
+
"""A more or less complete user-defined wrapper around list objects."""
|
| 1200 |
+
|
| 1201 |
+
def __init__(self, initlist=None):
|
| 1202 |
+
self.data = []
|
| 1203 |
+
if initlist is not None:
|
| 1204 |
+
# XXX should this accept an arbitrary sequence?
|
| 1205 |
+
if type(initlist) == type(self.data):
|
| 1206 |
+
self.data[:] = initlist
|
| 1207 |
+
elif isinstance(initlist, UserList):
|
| 1208 |
+
self.data[:] = initlist.data[:]
|
| 1209 |
+
else:
|
| 1210 |
+
self.data = list(initlist)
|
| 1211 |
+
|
| 1212 |
+
def __repr__(self):
|
| 1213 |
+
return repr(self.data)
|
| 1214 |
+
|
| 1215 |
+
def __lt__(self, other):
|
| 1216 |
+
return self.data < self.__cast(other)
|
| 1217 |
+
|
| 1218 |
+
def __le__(self, other):
|
| 1219 |
+
return self.data <= self.__cast(other)
|
| 1220 |
+
|
| 1221 |
+
def __eq__(self, other):
|
| 1222 |
+
return self.data == self.__cast(other)
|
| 1223 |
+
|
| 1224 |
+
def __gt__(self, other):
|
| 1225 |
+
return self.data > self.__cast(other)
|
| 1226 |
+
|
| 1227 |
+
def __ge__(self, other):
|
| 1228 |
+
return self.data >= self.__cast(other)
|
| 1229 |
+
|
| 1230 |
+
def __cast(self, other):
|
| 1231 |
+
return other.data if isinstance(other, UserList) else other
|
| 1232 |
+
|
| 1233 |
+
def __contains__(self, item):
|
| 1234 |
+
return item in self.data
|
| 1235 |
+
|
| 1236 |
+
def __len__(self):
|
| 1237 |
+
return len(self.data)
|
| 1238 |
+
|
| 1239 |
+
def __getitem__(self, i):
|
| 1240 |
+
if isinstance(i, slice):
|
| 1241 |
+
return self.__class__(self.data[i])
|
| 1242 |
+
else:
|
| 1243 |
+
return self.data[i]
|
| 1244 |
+
|
| 1245 |
+
def __setitem__(self, i, item):
|
| 1246 |
+
self.data[i] = item
|
| 1247 |
+
|
| 1248 |
+
def __delitem__(self, i):
|
| 1249 |
+
del self.data[i]
|
| 1250 |
+
|
| 1251 |
+
def __add__(self, other):
|
| 1252 |
+
if isinstance(other, UserList):
|
| 1253 |
+
return self.__class__(self.data + other.data)
|
| 1254 |
+
elif isinstance(other, type(self.data)):
|
| 1255 |
+
return self.__class__(self.data + other)
|
| 1256 |
+
return self.__class__(self.data + list(other))
|
| 1257 |
+
|
| 1258 |
+
def __radd__(self, other):
|
| 1259 |
+
if isinstance(other, UserList):
|
| 1260 |
+
return self.__class__(other.data + self.data)
|
| 1261 |
+
elif isinstance(other, type(self.data)):
|
| 1262 |
+
return self.__class__(other + self.data)
|
| 1263 |
+
return self.__class__(list(other) + self.data)
|
| 1264 |
+
|
| 1265 |
+
def __iadd__(self, other):
|
| 1266 |
+
if isinstance(other, UserList):
|
| 1267 |
+
self.data += other.data
|
| 1268 |
+
elif isinstance(other, type(self.data)):
|
| 1269 |
+
self.data += other
|
| 1270 |
+
else:
|
| 1271 |
+
self.data += list(other)
|
| 1272 |
+
return self
|
| 1273 |
+
|
| 1274 |
+
def __mul__(self, n):
|
| 1275 |
+
return self.__class__(self.data * n)
|
| 1276 |
+
|
| 1277 |
+
__rmul__ = __mul__
|
| 1278 |
+
|
| 1279 |
+
def __imul__(self, n):
|
| 1280 |
+
self.data *= n
|
| 1281 |
+
return self
|
| 1282 |
+
|
| 1283 |
+
def __copy__(self):
|
| 1284 |
+
inst = self.__class__.__new__(self.__class__)
|
| 1285 |
+
inst.__dict__.update(self.__dict__)
|
| 1286 |
+
# Create a copy and avoid triggering descriptors
|
| 1287 |
+
inst.__dict__["data"] = self.__dict__["data"][:]
|
| 1288 |
+
return inst
|
| 1289 |
+
|
| 1290 |
+
def append(self, item):
|
| 1291 |
+
self.data.append(item)
|
| 1292 |
+
|
| 1293 |
+
def insert(self, i, item):
|
| 1294 |
+
self.data.insert(i, item)
|
| 1295 |
+
|
| 1296 |
+
def pop(self, i=-1):
|
| 1297 |
+
return self.data.pop(i)
|
| 1298 |
+
|
| 1299 |
+
def remove(self, item):
|
| 1300 |
+
self.data.remove(item)
|
| 1301 |
+
|
| 1302 |
+
def clear(self):
|
| 1303 |
+
self.data.clear()
|
| 1304 |
+
|
| 1305 |
+
def copy(self):
|
| 1306 |
+
return self.__class__(self)
|
| 1307 |
+
|
| 1308 |
+
def count(self, item):
|
| 1309 |
+
return self.data.count(item)
|
| 1310 |
+
|
| 1311 |
+
def index(self, item, *args):
|
| 1312 |
+
return self.data.index(item, *args)
|
| 1313 |
+
|
| 1314 |
+
def reverse(self):
|
| 1315 |
+
self.data.reverse()
|
| 1316 |
+
|
| 1317 |
+
def sort(self, /, *args, **kwds):
|
| 1318 |
+
self.data.sort(*args, **kwds)
|
| 1319 |
+
|
| 1320 |
+
def extend(self, other):
|
| 1321 |
+
if isinstance(other, UserList):
|
| 1322 |
+
self.data.extend(other.data)
|
| 1323 |
+
else:
|
| 1324 |
+
self.data.extend(other)
|
| 1325 |
+
|
| 1326 |
+
|
| 1327 |
+
################################################################################
|
| 1328 |
+
### UserString
|
| 1329 |
+
################################################################################
|
| 1330 |
+
|
| 1331 |
+
class UserString(_collections_abc.Sequence):
|
| 1332 |
+
|
| 1333 |
+
def __init__(self, seq):
|
| 1334 |
+
if isinstance(seq, str):
|
| 1335 |
+
self.data = seq
|
| 1336 |
+
elif isinstance(seq, UserString):
|
| 1337 |
+
self.data = seq.data[:]
|
| 1338 |
+
else:
|
| 1339 |
+
self.data = str(seq)
|
| 1340 |
+
|
| 1341 |
+
def __str__(self):
|
| 1342 |
+
return str(self.data)
|
| 1343 |
+
|
| 1344 |
+
def __repr__(self):
|
| 1345 |
+
return repr(self.data)
|
| 1346 |
+
|
| 1347 |
+
def __int__(self):
|
| 1348 |
+
return int(self.data)
|
| 1349 |
+
|
| 1350 |
+
def __float__(self):
|
| 1351 |
+
return float(self.data)
|
| 1352 |
+
|
| 1353 |
+
def __complex__(self):
|
| 1354 |
+
return complex(self.data)
|
| 1355 |
+
|
| 1356 |
+
def __hash__(self):
|
| 1357 |
+
return hash(self.data)
|
| 1358 |
+
|
| 1359 |
+
def __getnewargs__(self):
|
| 1360 |
+
return (self.data[:],)
|
| 1361 |
+
|
| 1362 |
+
def __eq__(self, string):
|
| 1363 |
+
if isinstance(string, UserString):
|
| 1364 |
+
return self.data == string.data
|
| 1365 |
+
return self.data == string
|
| 1366 |
+
|
| 1367 |
+
def __lt__(self, string):
|
| 1368 |
+
if isinstance(string, UserString):
|
| 1369 |
+
return self.data < string.data
|
| 1370 |
+
return self.data < string
|
| 1371 |
+
|
| 1372 |
+
def __le__(self, string):
|
| 1373 |
+
if isinstance(string, UserString):
|
| 1374 |
+
return self.data <= string.data
|
| 1375 |
+
return self.data <= string
|
| 1376 |
+
|
| 1377 |
+
def __gt__(self, string):
|
| 1378 |
+
if isinstance(string, UserString):
|
| 1379 |
+
return self.data > string.data
|
| 1380 |
+
return self.data > string
|
| 1381 |
+
|
| 1382 |
+
def __ge__(self, string):
|
| 1383 |
+
if isinstance(string, UserString):
|
| 1384 |
+
return self.data >= string.data
|
| 1385 |
+
return self.data >= string
|
| 1386 |
+
|
| 1387 |
+
def __contains__(self, char):
|
| 1388 |
+
if isinstance(char, UserString):
|
| 1389 |
+
char = char.data
|
| 1390 |
+
return char in self.data
|
| 1391 |
+
|
| 1392 |
+
def __len__(self):
|
| 1393 |
+
return len(self.data)
|
| 1394 |
+
|
| 1395 |
+
def __getitem__(self, index):
|
| 1396 |
+
return self.__class__(self.data[index])
|
| 1397 |
+
|
| 1398 |
+
def __add__(self, other):
|
| 1399 |
+
if isinstance(other, UserString):
|
| 1400 |
+
return self.__class__(self.data + other.data)
|
| 1401 |
+
elif isinstance(other, str):
|
| 1402 |
+
return self.__class__(self.data + other)
|
| 1403 |
+
return self.__class__(self.data + str(other))
|
| 1404 |
+
|
| 1405 |
+
def __radd__(self, other):
|
| 1406 |
+
if isinstance(other, str):
|
| 1407 |
+
return self.__class__(other + self.data)
|
| 1408 |
+
return self.__class__(str(other) + self.data)
|
| 1409 |
+
|
| 1410 |
+
def __mul__(self, n):
|
| 1411 |
+
return self.__class__(self.data * n)
|
| 1412 |
+
|
| 1413 |
+
__rmul__ = __mul__
|
| 1414 |
+
|
| 1415 |
+
def __mod__(self, args):
|
| 1416 |
+
return self.__class__(self.data % args)
|
| 1417 |
+
|
| 1418 |
+
def __rmod__(self, template):
|
| 1419 |
+
return self.__class__(str(template) % self)
|
| 1420 |
+
|
| 1421 |
+
# the following methods are defined in alphabetical order:
|
| 1422 |
+
def capitalize(self):
|
| 1423 |
+
return self.__class__(self.data.capitalize())
|
| 1424 |
+
|
| 1425 |
+
def casefold(self):
|
| 1426 |
+
return self.__class__(self.data.casefold())
|
| 1427 |
+
|
| 1428 |
+
def center(self, width, *args):
|
| 1429 |
+
return self.__class__(self.data.center(width, *args))
|
| 1430 |
+
|
| 1431 |
+
def count(self, sub, start=0, end=_sys.maxsize):
|
| 1432 |
+
if isinstance(sub, UserString):
|
| 1433 |
+
sub = sub.data
|
| 1434 |
+
return self.data.count(sub, start, end)
|
| 1435 |
+
|
| 1436 |
+
def removeprefix(self, prefix, /):
|
| 1437 |
+
if isinstance(prefix, UserString):
|
| 1438 |
+
prefix = prefix.data
|
| 1439 |
+
return self.__class__(self.data.removeprefix(prefix))
|
| 1440 |
+
|
| 1441 |
+
def removesuffix(self, suffix, /):
|
| 1442 |
+
if isinstance(suffix, UserString):
|
| 1443 |
+
suffix = suffix.data
|
| 1444 |
+
return self.__class__(self.data.removesuffix(suffix))
|
| 1445 |
+
|
| 1446 |
+
def encode(self, encoding='utf-8', errors='strict'):
|
| 1447 |
+
encoding = 'utf-8' if encoding is None else encoding
|
| 1448 |
+
errors = 'strict' if errors is None else errors
|
| 1449 |
+
return self.data.encode(encoding, errors)
|
| 1450 |
+
|
| 1451 |
+
def endswith(self, suffix, start=0, end=_sys.maxsize):
|
| 1452 |
+
return self.data.endswith(suffix, start, end)
|
| 1453 |
+
|
| 1454 |
+
def expandtabs(self, tabsize=8):
|
| 1455 |
+
return self.__class__(self.data.expandtabs(tabsize))
|
| 1456 |
+
|
| 1457 |
+
def find(self, sub, start=0, end=_sys.maxsize):
|
| 1458 |
+
if isinstance(sub, UserString):
|
| 1459 |
+
sub = sub.data
|
| 1460 |
+
return self.data.find(sub, start, end)
|
| 1461 |
+
|
| 1462 |
+
def format(self, /, *args, **kwds):
|
| 1463 |
+
return self.data.format(*args, **kwds)
|
| 1464 |
+
|
| 1465 |
+
def format_map(self, mapping):
|
| 1466 |
+
return self.data.format_map(mapping)
|
| 1467 |
+
|
| 1468 |
+
def index(self, sub, start=0, end=_sys.maxsize):
|
| 1469 |
+
return self.data.index(sub, start, end)
|
| 1470 |
+
|
| 1471 |
+
def isalpha(self):
|
| 1472 |
+
return self.data.isalpha()
|
| 1473 |
+
|
| 1474 |
+
def isalnum(self):
|
| 1475 |
+
return self.data.isalnum()
|
| 1476 |
+
|
| 1477 |
+
def isascii(self):
|
| 1478 |
+
return self.data.isascii()
|
| 1479 |
+
|
| 1480 |
+
def isdecimal(self):
|
| 1481 |
+
return self.data.isdecimal()
|
| 1482 |
+
|
| 1483 |
+
def isdigit(self):
|
| 1484 |
+
return self.data.isdigit()
|
| 1485 |
+
|
| 1486 |
+
def isidentifier(self):
|
| 1487 |
+
return self.data.isidentifier()
|
| 1488 |
+
|
| 1489 |
+
def islower(self):
|
| 1490 |
+
return self.data.islower()
|
| 1491 |
+
|
| 1492 |
+
def isnumeric(self):
|
| 1493 |
+
return self.data.isnumeric()
|
| 1494 |
+
|
| 1495 |
+
def isprintable(self):
|
| 1496 |
+
return self.data.isprintable()
|
| 1497 |
+
|
| 1498 |
+
def isspace(self):
|
| 1499 |
+
return self.data.isspace()
|
| 1500 |
+
|
| 1501 |
+
def istitle(self):
|
| 1502 |
+
return self.data.istitle()
|
| 1503 |
+
|
| 1504 |
+
def isupper(self):
|
| 1505 |
+
return self.data.isupper()
|
| 1506 |
+
|
| 1507 |
+
def join(self, seq):
|
| 1508 |
+
return self.data.join(seq)
|
| 1509 |
+
|
| 1510 |
+
def ljust(self, width, *args):
|
| 1511 |
+
return self.__class__(self.data.ljust(width, *args))
|
| 1512 |
+
|
| 1513 |
+
def lower(self):
|
| 1514 |
+
return self.__class__(self.data.lower())
|
| 1515 |
+
|
| 1516 |
+
def lstrip(self, chars=None):
|
| 1517 |
+
return self.__class__(self.data.lstrip(chars))
|
| 1518 |
+
|
| 1519 |
+
maketrans = str.maketrans
|
| 1520 |
+
|
| 1521 |
+
def partition(self, sep):
|
| 1522 |
+
return self.data.partition(sep)
|
| 1523 |
+
|
| 1524 |
+
def replace(self, old, new, maxsplit=-1):
|
| 1525 |
+
if isinstance(old, UserString):
|
| 1526 |
+
old = old.data
|
| 1527 |
+
if isinstance(new, UserString):
|
| 1528 |
+
new = new.data
|
| 1529 |
+
return self.__class__(self.data.replace(old, new, maxsplit))
|
| 1530 |
+
|
| 1531 |
+
def rfind(self, sub, start=0, end=_sys.maxsize):
|
| 1532 |
+
if isinstance(sub, UserString):
|
| 1533 |
+
sub = sub.data
|
| 1534 |
+
return self.data.rfind(sub, start, end)
|
| 1535 |
+
|
| 1536 |
+
def rindex(self, sub, start=0, end=_sys.maxsize):
|
| 1537 |
+
return self.data.rindex(sub, start, end)
|
| 1538 |
+
|
| 1539 |
+
def rjust(self, width, *args):
|
| 1540 |
+
return self.__class__(self.data.rjust(width, *args))
|
| 1541 |
+
|
| 1542 |
+
def rpartition(self, sep):
|
| 1543 |
+
return self.data.rpartition(sep)
|
| 1544 |
+
|
| 1545 |
+
def rstrip(self, chars=None):
|
| 1546 |
+
return self.__class__(self.data.rstrip(chars))
|
| 1547 |
+
|
| 1548 |
+
def split(self, sep=None, maxsplit=-1):
|
| 1549 |
+
return self.data.split(sep, maxsplit)
|
| 1550 |
+
|
| 1551 |
+
def rsplit(self, sep=None, maxsplit=-1):
|
| 1552 |
+
return self.data.rsplit(sep, maxsplit)
|
| 1553 |
+
|
| 1554 |
+
def splitlines(self, keepends=False):
|
| 1555 |
+
return self.data.splitlines(keepends)
|
| 1556 |
+
|
| 1557 |
+
def startswith(self, prefix, start=0, end=_sys.maxsize):
|
| 1558 |
+
return self.data.startswith(prefix, start, end)
|
| 1559 |
+
|
| 1560 |
+
def strip(self, chars=None):
|
| 1561 |
+
return self.__class__(self.data.strip(chars))
|
| 1562 |
+
|
| 1563 |
+
def swapcase(self):
|
| 1564 |
+
return self.__class__(self.data.swapcase())
|
| 1565 |
+
|
| 1566 |
+
def title(self):
|
| 1567 |
+
return self.__class__(self.data.title())
|
| 1568 |
+
|
| 1569 |
+
def translate(self, *args):
|
| 1570 |
+
return self.__class__(self.data.translate(*args))
|
| 1571 |
+
|
| 1572 |
+
def upper(self):
|
| 1573 |
+
return self.__class__(self.data.upper())
|
| 1574 |
+
|
| 1575 |
+
def zfill(self, width):
|
| 1576 |
+
return self.__class__(self.data.zfill(width))
|
micromamba_root/envs/pytorch_env/Lib/collections/abc.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from _collections_abc import *
|
| 2 |
+
from _collections_abc import __all__
|
| 3 |
+
from _collections_abc import _CallableGenericAlias
|
micromamba_root/envs/pytorch_env/Lib/concurrent/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# This directory is a Python package.
|
micromamba_root/envs/pytorch_env/Lib/ctypes/__init__.py
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""create and manipulate C data types in Python"""
|
| 2 |
+
|
| 3 |
+
import os as _os, sys as _sys
|
| 4 |
+
import types as _types
|
| 5 |
+
|
| 6 |
+
__version__ = "1.1.0"
|
| 7 |
+
|
| 8 |
+
from _ctypes import Union, Structure, Array
|
| 9 |
+
from _ctypes import _Pointer
|
| 10 |
+
from _ctypes import CFuncPtr as _CFuncPtr
|
| 11 |
+
from _ctypes import __version__ as _ctypes_version
|
| 12 |
+
from _ctypes import RTLD_LOCAL, RTLD_GLOBAL
|
| 13 |
+
from _ctypes import ArgumentError
|
| 14 |
+
|
| 15 |
+
from struct import calcsize as _calcsize
|
| 16 |
+
|
| 17 |
+
if __version__ != _ctypes_version:
|
| 18 |
+
raise Exception("Version number mismatch", __version__, _ctypes_version)
|
| 19 |
+
|
| 20 |
+
if _os.name == "nt":
|
| 21 |
+
from _ctypes import FormatError
|
| 22 |
+
|
| 23 |
+
DEFAULT_MODE = RTLD_LOCAL
|
| 24 |
+
if _os.name == "posix" and _sys.platform == "darwin":
|
| 25 |
+
# On OS X 10.3, we use RTLD_GLOBAL as default mode
|
| 26 |
+
# because RTLD_LOCAL does not work at least on some
|
| 27 |
+
# libraries. OS X 10.3 is Darwin 7, so we check for
|
| 28 |
+
# that.
|
| 29 |
+
|
| 30 |
+
if int(_os.uname().release.split('.')[0]) < 8:
|
| 31 |
+
DEFAULT_MODE = RTLD_GLOBAL
|
| 32 |
+
|
| 33 |
+
from _ctypes import FUNCFLAG_CDECL as _FUNCFLAG_CDECL, \
|
| 34 |
+
FUNCFLAG_PYTHONAPI as _FUNCFLAG_PYTHONAPI, \
|
| 35 |
+
FUNCFLAG_USE_ERRNO as _FUNCFLAG_USE_ERRNO, \
|
| 36 |
+
FUNCFLAG_USE_LASTERROR as _FUNCFLAG_USE_LASTERROR
|
| 37 |
+
|
| 38 |
+
# WINOLEAPI -> HRESULT
|
| 39 |
+
# WINOLEAPI_(type)
|
| 40 |
+
#
|
| 41 |
+
# STDMETHODCALLTYPE
|
| 42 |
+
#
|
| 43 |
+
# STDMETHOD(name)
|
| 44 |
+
# STDMETHOD_(type, name)
|
| 45 |
+
#
|
| 46 |
+
# STDAPICALLTYPE
|
| 47 |
+
|
| 48 |
+
def create_string_buffer(init, size=None):
|
| 49 |
+
"""create_string_buffer(aBytes) -> character array
|
| 50 |
+
create_string_buffer(anInteger) -> character array
|
| 51 |
+
create_string_buffer(aBytes, anInteger) -> character array
|
| 52 |
+
"""
|
| 53 |
+
if isinstance(init, bytes):
|
| 54 |
+
if size is None:
|
| 55 |
+
size = len(init)+1
|
| 56 |
+
_sys.audit("ctypes.create_string_buffer", init, size)
|
| 57 |
+
buftype = c_char * size
|
| 58 |
+
buf = buftype()
|
| 59 |
+
buf.value = init
|
| 60 |
+
return buf
|
| 61 |
+
elif isinstance(init, int):
|
| 62 |
+
_sys.audit("ctypes.create_string_buffer", None, init)
|
| 63 |
+
buftype = c_char * init
|
| 64 |
+
buf = buftype()
|
| 65 |
+
return buf
|
| 66 |
+
raise TypeError(init)
|
| 67 |
+
|
| 68 |
+
# Alias to create_string_buffer() for backward compatibility
|
| 69 |
+
c_buffer = create_string_buffer
|
| 70 |
+
|
| 71 |
+
_c_functype_cache = {}
|
| 72 |
+
def CFUNCTYPE(restype, *argtypes, **kw):
|
| 73 |
+
"""CFUNCTYPE(restype, *argtypes,
|
| 74 |
+
use_errno=False, use_last_error=False) -> function prototype.
|
| 75 |
+
|
| 76 |
+
restype: the result type
|
| 77 |
+
argtypes: a sequence specifying the argument types
|
| 78 |
+
|
| 79 |
+
The function prototype can be called in different ways to create a
|
| 80 |
+
callable object:
|
| 81 |
+
|
| 82 |
+
prototype(integer address) -> foreign function
|
| 83 |
+
prototype(callable) -> create and return a C callable function from callable
|
| 84 |
+
prototype(integer index, method name[, paramflags]) -> foreign function calling a COM method
|
| 85 |
+
prototype((ordinal number, dll object)[, paramflags]) -> foreign function exported by ordinal
|
| 86 |
+
prototype((function name, dll object)[, paramflags]) -> foreign function exported by name
|
| 87 |
+
"""
|
| 88 |
+
flags = _FUNCFLAG_CDECL
|
| 89 |
+
if kw.pop("use_errno", False):
|
| 90 |
+
flags |= _FUNCFLAG_USE_ERRNO
|
| 91 |
+
if kw.pop("use_last_error", False):
|
| 92 |
+
flags |= _FUNCFLAG_USE_LASTERROR
|
| 93 |
+
if kw:
|
| 94 |
+
raise ValueError("unexpected keyword argument(s) %s" % kw.keys())
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
return _c_functype_cache[(restype, argtypes, flags)]
|
| 98 |
+
except KeyError:
|
| 99 |
+
pass
|
| 100 |
+
|
| 101 |
+
class CFunctionType(_CFuncPtr):
|
| 102 |
+
_argtypes_ = argtypes
|
| 103 |
+
_restype_ = restype
|
| 104 |
+
_flags_ = flags
|
| 105 |
+
_c_functype_cache[(restype, argtypes, flags)] = CFunctionType
|
| 106 |
+
return CFunctionType
|
| 107 |
+
|
| 108 |
+
if _os.name == "nt":
|
| 109 |
+
from _ctypes import LoadLibrary as _dlopen
|
| 110 |
+
from _ctypes import FUNCFLAG_STDCALL as _FUNCFLAG_STDCALL
|
| 111 |
+
|
| 112 |
+
_win_functype_cache = {}
|
| 113 |
+
def WINFUNCTYPE(restype, *argtypes, **kw):
|
| 114 |
+
# docstring set later (very similar to CFUNCTYPE.__doc__)
|
| 115 |
+
flags = _FUNCFLAG_STDCALL
|
| 116 |
+
if kw.pop("use_errno", False):
|
| 117 |
+
flags |= _FUNCFLAG_USE_ERRNO
|
| 118 |
+
if kw.pop("use_last_error", False):
|
| 119 |
+
flags |= _FUNCFLAG_USE_LASTERROR
|
| 120 |
+
if kw:
|
| 121 |
+
raise ValueError("unexpected keyword argument(s) %s" % kw.keys())
|
| 122 |
+
|
| 123 |
+
try:
|
| 124 |
+
return _win_functype_cache[(restype, argtypes, flags)]
|
| 125 |
+
except KeyError:
|
| 126 |
+
pass
|
| 127 |
+
|
| 128 |
+
class WinFunctionType(_CFuncPtr):
|
| 129 |
+
_argtypes_ = argtypes
|
| 130 |
+
_restype_ = restype
|
| 131 |
+
_flags_ = flags
|
| 132 |
+
_win_functype_cache[(restype, argtypes, flags)] = WinFunctionType
|
| 133 |
+
return WinFunctionType
|
| 134 |
+
if WINFUNCTYPE.__doc__:
|
| 135 |
+
WINFUNCTYPE.__doc__ = CFUNCTYPE.__doc__.replace("CFUNCTYPE", "WINFUNCTYPE")
|
| 136 |
+
|
| 137 |
+
elif _os.name == "posix":
|
| 138 |
+
from _ctypes import dlopen as _dlopen
|
| 139 |
+
|
| 140 |
+
from _ctypes import sizeof, byref, addressof, alignment, resize
|
| 141 |
+
from _ctypes import get_errno, set_errno
|
| 142 |
+
from _ctypes import _SimpleCData
|
| 143 |
+
|
| 144 |
+
def _check_size(typ, typecode=None):
|
| 145 |
+
# Check if sizeof(ctypes_type) against struct.calcsize. This
|
| 146 |
+
# should protect somewhat against a misconfigured libffi.
|
| 147 |
+
from struct import calcsize
|
| 148 |
+
if typecode is None:
|
| 149 |
+
# Most _type_ codes are the same as used in struct
|
| 150 |
+
typecode = typ._type_
|
| 151 |
+
actual, required = sizeof(typ), calcsize(typecode)
|
| 152 |
+
if actual != required:
|
| 153 |
+
raise SystemError("sizeof(%s) wrong: %d instead of %d" % \
|
| 154 |
+
(typ, actual, required))
|
| 155 |
+
|
| 156 |
+
class py_object(_SimpleCData):
|
| 157 |
+
_type_ = "O"
|
| 158 |
+
def __repr__(self):
|
| 159 |
+
try:
|
| 160 |
+
return super().__repr__()
|
| 161 |
+
except ValueError:
|
| 162 |
+
return "%s(<NULL>)" % type(self).__name__
|
| 163 |
+
_check_size(py_object, "P")
|
| 164 |
+
|
| 165 |
+
class c_short(_SimpleCData):
|
| 166 |
+
_type_ = "h"
|
| 167 |
+
_check_size(c_short)
|
| 168 |
+
|
| 169 |
+
class c_ushort(_SimpleCData):
|
| 170 |
+
_type_ = "H"
|
| 171 |
+
_check_size(c_ushort)
|
| 172 |
+
|
| 173 |
+
class c_long(_SimpleCData):
|
| 174 |
+
_type_ = "l"
|
| 175 |
+
_check_size(c_long)
|
| 176 |
+
|
| 177 |
+
class c_ulong(_SimpleCData):
|
| 178 |
+
_type_ = "L"
|
| 179 |
+
_check_size(c_ulong)
|
| 180 |
+
|
| 181 |
+
if _calcsize("i") == _calcsize("l"):
|
| 182 |
+
# if int and long have the same size, make c_int an alias for c_long
|
| 183 |
+
c_int = c_long
|
| 184 |
+
c_uint = c_ulong
|
| 185 |
+
else:
|
| 186 |
+
class c_int(_SimpleCData):
|
| 187 |
+
_type_ = "i"
|
| 188 |
+
_check_size(c_int)
|
| 189 |
+
|
| 190 |
+
class c_uint(_SimpleCData):
|
| 191 |
+
_type_ = "I"
|
| 192 |
+
_check_size(c_uint)
|
| 193 |
+
|
| 194 |
+
class c_float(_SimpleCData):
|
| 195 |
+
_type_ = "f"
|
| 196 |
+
_check_size(c_float)
|
| 197 |
+
|
| 198 |
+
class c_double(_SimpleCData):
|
| 199 |
+
_type_ = "d"
|
| 200 |
+
_check_size(c_double)
|
| 201 |
+
|
| 202 |
+
class c_longdouble(_SimpleCData):
|
| 203 |
+
_type_ = "g"
|
| 204 |
+
if sizeof(c_longdouble) == sizeof(c_double):
|
| 205 |
+
c_longdouble = c_double
|
| 206 |
+
|
| 207 |
+
if _calcsize("l") == _calcsize("q"):
|
| 208 |
+
# if long and long long have the same size, make c_longlong an alias for c_long
|
| 209 |
+
c_longlong = c_long
|
| 210 |
+
c_ulonglong = c_ulong
|
| 211 |
+
else:
|
| 212 |
+
class c_longlong(_SimpleCData):
|
| 213 |
+
_type_ = "q"
|
| 214 |
+
_check_size(c_longlong)
|
| 215 |
+
|
| 216 |
+
class c_ulonglong(_SimpleCData):
|
| 217 |
+
_type_ = "Q"
|
| 218 |
+
## def from_param(cls, val):
|
| 219 |
+
## return ('d', float(val), val)
|
| 220 |
+
## from_param = classmethod(from_param)
|
| 221 |
+
_check_size(c_ulonglong)
|
| 222 |
+
|
| 223 |
+
class c_ubyte(_SimpleCData):
|
| 224 |
+
_type_ = "B"
|
| 225 |
+
c_ubyte.__ctype_le__ = c_ubyte.__ctype_be__ = c_ubyte
|
| 226 |
+
# backward compatibility:
|
| 227 |
+
##c_uchar = c_ubyte
|
| 228 |
+
_check_size(c_ubyte)
|
| 229 |
+
|
| 230 |
+
class c_byte(_SimpleCData):
|
| 231 |
+
_type_ = "b"
|
| 232 |
+
c_byte.__ctype_le__ = c_byte.__ctype_be__ = c_byte
|
| 233 |
+
_check_size(c_byte)
|
| 234 |
+
|
| 235 |
+
class c_char(_SimpleCData):
|
| 236 |
+
_type_ = "c"
|
| 237 |
+
c_char.__ctype_le__ = c_char.__ctype_be__ = c_char
|
| 238 |
+
_check_size(c_char)
|
| 239 |
+
|
| 240 |
+
class c_char_p(_SimpleCData):
|
| 241 |
+
_type_ = "z"
|
| 242 |
+
def __repr__(self):
|
| 243 |
+
return "%s(%s)" % (self.__class__.__name__, c_void_p.from_buffer(self).value)
|
| 244 |
+
_check_size(c_char_p, "P")
|
| 245 |
+
|
| 246 |
+
class c_void_p(_SimpleCData):
|
| 247 |
+
_type_ = "P"
|
| 248 |
+
c_voidp = c_void_p # backwards compatibility (to a bug)
|
| 249 |
+
_check_size(c_void_p)
|
| 250 |
+
|
| 251 |
+
class c_bool(_SimpleCData):
|
| 252 |
+
_type_ = "?"
|
| 253 |
+
|
| 254 |
+
from _ctypes import POINTER, pointer, _pointer_type_cache
|
| 255 |
+
|
| 256 |
+
class c_wchar_p(_SimpleCData):
|
| 257 |
+
_type_ = "Z"
|
| 258 |
+
def __repr__(self):
|
| 259 |
+
return "%s(%s)" % (self.__class__.__name__, c_void_p.from_buffer(self).value)
|
| 260 |
+
|
| 261 |
+
class c_wchar(_SimpleCData):
|
| 262 |
+
_type_ = "u"
|
| 263 |
+
|
| 264 |
+
def _reset_cache():
|
| 265 |
+
_pointer_type_cache.clear()
|
| 266 |
+
_c_functype_cache.clear()
|
| 267 |
+
if _os.name == "nt":
|
| 268 |
+
_win_functype_cache.clear()
|
| 269 |
+
# _SimpleCData.c_wchar_p_from_param
|
| 270 |
+
POINTER(c_wchar).from_param = c_wchar_p.from_param
|
| 271 |
+
# _SimpleCData.c_char_p_from_param
|
| 272 |
+
POINTER(c_char).from_param = c_char_p.from_param
|
| 273 |
+
_pointer_type_cache[None] = c_void_p
|
| 274 |
+
|
| 275 |
+
def create_unicode_buffer(init, size=None):
|
| 276 |
+
"""create_unicode_buffer(aString) -> character array
|
| 277 |
+
create_unicode_buffer(anInteger) -> character array
|
| 278 |
+
create_unicode_buffer(aString, anInteger) -> character array
|
| 279 |
+
"""
|
| 280 |
+
if isinstance(init, str):
|
| 281 |
+
if size is None:
|
| 282 |
+
if sizeof(c_wchar) == 2:
|
| 283 |
+
# UTF-16 requires a surrogate pair (2 wchar_t) for non-BMP
|
| 284 |
+
# characters (outside [U+0000; U+FFFF] range). +1 for trailing
|
| 285 |
+
# NUL character.
|
| 286 |
+
size = sum(2 if ord(c) > 0xFFFF else 1 for c in init) + 1
|
| 287 |
+
else:
|
| 288 |
+
# 32-bit wchar_t (1 wchar_t per Unicode character). +1 for
|
| 289 |
+
# trailing NUL character.
|
| 290 |
+
size = len(init) + 1
|
| 291 |
+
_sys.audit("ctypes.create_unicode_buffer", init, size)
|
| 292 |
+
buftype = c_wchar * size
|
| 293 |
+
buf = buftype()
|
| 294 |
+
buf.value = init
|
| 295 |
+
return buf
|
| 296 |
+
elif isinstance(init, int):
|
| 297 |
+
_sys.audit("ctypes.create_unicode_buffer", None, init)
|
| 298 |
+
buftype = c_wchar * init
|
| 299 |
+
buf = buftype()
|
| 300 |
+
return buf
|
| 301 |
+
raise TypeError(init)
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
# XXX Deprecated
|
| 305 |
+
def SetPointerType(pointer, cls):
|
| 306 |
+
if _pointer_type_cache.get(cls, None) is not None:
|
| 307 |
+
raise RuntimeError("This type already exists in the cache")
|
| 308 |
+
if id(pointer) not in _pointer_type_cache:
|
| 309 |
+
raise RuntimeError("What's this???")
|
| 310 |
+
pointer.set_type(cls)
|
| 311 |
+
_pointer_type_cache[cls] = pointer
|
| 312 |
+
del _pointer_type_cache[id(pointer)]
|
| 313 |
+
|
| 314 |
+
# XXX Deprecated
|
| 315 |
+
def ARRAY(typ, len):
|
| 316 |
+
return typ * len
|
| 317 |
+
|
| 318 |
+
################################################################
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class CDLL(object):
|
| 322 |
+
"""An instance of this class represents a loaded dll/shared
|
| 323 |
+
library, exporting functions using the standard C calling
|
| 324 |
+
convention (named 'cdecl' on Windows).
|
| 325 |
+
|
| 326 |
+
The exported functions can be accessed as attributes, or by
|
| 327 |
+
indexing with the function name. Examples:
|
| 328 |
+
|
| 329 |
+
<obj>.qsort -> callable object
|
| 330 |
+
<obj>['qsort'] -> callable object
|
| 331 |
+
|
| 332 |
+
Calling the functions releases the Python GIL during the call and
|
| 333 |
+
reacquires it afterwards.
|
| 334 |
+
"""
|
| 335 |
+
_func_flags_ = _FUNCFLAG_CDECL
|
| 336 |
+
_func_restype_ = c_int
|
| 337 |
+
# default values for repr
|
| 338 |
+
_name = '<uninitialized>'
|
| 339 |
+
_handle = 0
|
| 340 |
+
_FuncPtr = None
|
| 341 |
+
|
| 342 |
+
def __init__(self, name, mode=DEFAULT_MODE, handle=None,
|
| 343 |
+
use_errno=False,
|
| 344 |
+
use_last_error=False,
|
| 345 |
+
winmode=None):
|
| 346 |
+
self._name = name
|
| 347 |
+
flags = self._func_flags_
|
| 348 |
+
if use_errno:
|
| 349 |
+
flags |= _FUNCFLAG_USE_ERRNO
|
| 350 |
+
if use_last_error:
|
| 351 |
+
flags |= _FUNCFLAG_USE_LASTERROR
|
| 352 |
+
if _sys.platform.startswith("aix"):
|
| 353 |
+
"""When the name contains ".a(" and ends with ")",
|
| 354 |
+
e.g., "libFOO.a(libFOO.so)" - this is taken to be an
|
| 355 |
+
archive(member) syntax for dlopen(), and the mode is adjusted.
|
| 356 |
+
Otherwise, name is presented to dlopen() as a file argument.
|
| 357 |
+
"""
|
| 358 |
+
if name and name.endswith(")") and ".a(" in name:
|
| 359 |
+
mode |= ( _os.RTLD_MEMBER | _os.RTLD_NOW )
|
| 360 |
+
if _os.name == "nt":
|
| 361 |
+
if winmode is not None:
|
| 362 |
+
mode = winmode
|
| 363 |
+
else:
|
| 364 |
+
import nt
|
| 365 |
+
mode = nt._LOAD_LIBRARY_SEARCH_DEFAULT_DIRS
|
| 366 |
+
if '/' in name or '\\' in name:
|
| 367 |
+
self._name = nt._getfullpathname(self._name)
|
| 368 |
+
mode |= nt._LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
|
| 369 |
+
|
| 370 |
+
class _FuncPtr(_CFuncPtr):
|
| 371 |
+
_flags_ = flags
|
| 372 |
+
_restype_ = self._func_restype_
|
| 373 |
+
self._FuncPtr = _FuncPtr
|
| 374 |
+
|
| 375 |
+
if handle is None:
|
| 376 |
+
self._handle = _dlopen(self._name, mode)
|
| 377 |
+
else:
|
| 378 |
+
self._handle = handle
|
| 379 |
+
|
| 380 |
+
def __repr__(self):
|
| 381 |
+
return "<%s '%s', handle %x at %#x>" % \
|
| 382 |
+
(self.__class__.__name__, self._name,
|
| 383 |
+
(self._handle & (_sys.maxsize*2 + 1)),
|
| 384 |
+
id(self) & (_sys.maxsize*2 + 1))
|
| 385 |
+
|
| 386 |
+
def __getattr__(self, name):
|
| 387 |
+
if name.startswith('__') and name.endswith('__'):
|
| 388 |
+
raise AttributeError(name)
|
| 389 |
+
func = self.__getitem__(name)
|
| 390 |
+
setattr(self, name, func)
|
| 391 |
+
return func
|
| 392 |
+
|
| 393 |
+
def __getitem__(self, name_or_ordinal):
|
| 394 |
+
func = self._FuncPtr((name_or_ordinal, self))
|
| 395 |
+
if not isinstance(name_or_ordinal, int):
|
| 396 |
+
func.__name__ = name_or_ordinal
|
| 397 |
+
return func
|
| 398 |
+
|
| 399 |
+
class PyDLL(CDLL):
|
| 400 |
+
"""This class represents the Python library itself. It allows
|
| 401 |
+
accessing Python API functions. The GIL is not released, and
|
| 402 |
+
Python exceptions are handled correctly.
|
| 403 |
+
"""
|
| 404 |
+
_func_flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
|
| 405 |
+
|
| 406 |
+
if _os.name == "nt":
|
| 407 |
+
|
| 408 |
+
class WinDLL(CDLL):
|
| 409 |
+
"""This class represents a dll exporting functions using the
|
| 410 |
+
Windows stdcall calling convention.
|
| 411 |
+
"""
|
| 412 |
+
_func_flags_ = _FUNCFLAG_STDCALL
|
| 413 |
+
|
| 414 |
+
# XXX Hm, what about HRESULT as normal parameter?
|
| 415 |
+
# Mustn't it derive from c_long then?
|
| 416 |
+
from _ctypes import _check_HRESULT, _SimpleCData
|
| 417 |
+
class HRESULT(_SimpleCData):
|
| 418 |
+
_type_ = "l"
|
| 419 |
+
# _check_retval_ is called with the function's result when it
|
| 420 |
+
# is used as restype. It checks for the FAILED bit, and
|
| 421 |
+
# raises an OSError if it is set.
|
| 422 |
+
#
|
| 423 |
+
# The _check_retval_ method is implemented in C, so that the
|
| 424 |
+
# method definition itself is not included in the traceback
|
| 425 |
+
# when it raises an error - that is what we want (and Python
|
| 426 |
+
# doesn't have a way to raise an exception in the caller's
|
| 427 |
+
# frame).
|
| 428 |
+
_check_retval_ = _check_HRESULT
|
| 429 |
+
|
| 430 |
+
class OleDLL(CDLL):
|
| 431 |
+
"""This class represents a dll exporting functions using the
|
| 432 |
+
Windows stdcall calling convention, and returning HRESULT.
|
| 433 |
+
HRESULT error values are automatically raised as OSError
|
| 434 |
+
exceptions.
|
| 435 |
+
"""
|
| 436 |
+
_func_flags_ = _FUNCFLAG_STDCALL
|
| 437 |
+
_func_restype_ = HRESULT
|
| 438 |
+
|
| 439 |
+
class LibraryLoader(object):
|
| 440 |
+
def __init__(self, dlltype):
|
| 441 |
+
self._dlltype = dlltype
|
| 442 |
+
|
| 443 |
+
def __getattr__(self, name):
|
| 444 |
+
if name[0] == '_':
|
| 445 |
+
raise AttributeError(name)
|
| 446 |
+
dll = self._dlltype(name)
|
| 447 |
+
setattr(self, name, dll)
|
| 448 |
+
return dll
|
| 449 |
+
|
| 450 |
+
def __getitem__(self, name):
|
| 451 |
+
return getattr(self, name)
|
| 452 |
+
|
| 453 |
+
def LoadLibrary(self, name):
|
| 454 |
+
return self._dlltype(name)
|
| 455 |
+
|
| 456 |
+
__class_getitem__ = classmethod(_types.GenericAlias)
|
| 457 |
+
|
| 458 |
+
cdll = LibraryLoader(CDLL)
|
| 459 |
+
pydll = LibraryLoader(PyDLL)
|
| 460 |
+
|
| 461 |
+
if _os.name == "nt":
|
| 462 |
+
pythonapi = PyDLL("python dll", None, _sys.dllhandle)
|
| 463 |
+
elif _sys.platform == "cygwin":
|
| 464 |
+
pythonapi = PyDLL("libpython%d.%d.dll" % _sys.version_info[:2])
|
| 465 |
+
else:
|
| 466 |
+
pythonapi = PyDLL(None)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
if _os.name == "nt":
|
| 470 |
+
windll = LibraryLoader(WinDLL)
|
| 471 |
+
oledll = LibraryLoader(OleDLL)
|
| 472 |
+
|
| 473 |
+
GetLastError = windll.kernel32.GetLastError
|
| 474 |
+
from _ctypes import get_last_error, set_last_error
|
| 475 |
+
|
| 476 |
+
def WinError(code=None, descr=None):
|
| 477 |
+
if code is None:
|
| 478 |
+
code = GetLastError()
|
| 479 |
+
if descr is None:
|
| 480 |
+
descr = FormatError(code).strip()
|
| 481 |
+
return OSError(None, descr, None, code)
|
| 482 |
+
|
| 483 |
+
if sizeof(c_uint) == sizeof(c_void_p):
|
| 484 |
+
c_size_t = c_uint
|
| 485 |
+
c_ssize_t = c_int
|
| 486 |
+
elif sizeof(c_ulong) == sizeof(c_void_p):
|
| 487 |
+
c_size_t = c_ulong
|
| 488 |
+
c_ssize_t = c_long
|
| 489 |
+
elif sizeof(c_ulonglong) == sizeof(c_void_p):
|
| 490 |
+
c_size_t = c_ulonglong
|
| 491 |
+
c_ssize_t = c_longlong
|
| 492 |
+
|
| 493 |
+
# functions
|
| 494 |
+
|
| 495 |
+
from _ctypes import _memmove_addr, _memset_addr, _string_at_addr, _cast_addr
|
| 496 |
+
|
| 497 |
+
## void *memmove(void *, const void *, size_t);
|
| 498 |
+
memmove = CFUNCTYPE(c_void_p, c_void_p, c_void_p, c_size_t)(_memmove_addr)
|
| 499 |
+
|
| 500 |
+
## void *memset(void *, int, size_t)
|
| 501 |
+
memset = CFUNCTYPE(c_void_p, c_void_p, c_int, c_size_t)(_memset_addr)
|
| 502 |
+
|
| 503 |
+
def PYFUNCTYPE(restype, *argtypes):
|
| 504 |
+
class CFunctionType(_CFuncPtr):
|
| 505 |
+
_argtypes_ = argtypes
|
| 506 |
+
_restype_ = restype
|
| 507 |
+
_flags_ = _FUNCFLAG_CDECL | _FUNCFLAG_PYTHONAPI
|
| 508 |
+
return CFunctionType
|
| 509 |
+
|
| 510 |
+
_cast = PYFUNCTYPE(py_object, c_void_p, py_object, py_object)(_cast_addr)
|
| 511 |
+
def cast(obj, typ):
|
| 512 |
+
return _cast(obj, obj, typ)
|
| 513 |
+
|
| 514 |
+
_string_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_string_at_addr)
|
| 515 |
+
def string_at(ptr, size=-1):
|
| 516 |
+
"""string_at(addr[, size]) -> string
|
| 517 |
+
|
| 518 |
+
Return the string at addr."""
|
| 519 |
+
return _string_at(ptr, size)
|
| 520 |
+
|
| 521 |
+
try:
|
| 522 |
+
from _ctypes import _wstring_at_addr
|
| 523 |
+
except ImportError:
|
| 524 |
+
pass
|
| 525 |
+
else:
|
| 526 |
+
_wstring_at = PYFUNCTYPE(py_object, c_void_p, c_int)(_wstring_at_addr)
|
| 527 |
+
def wstring_at(ptr, size=-1):
|
| 528 |
+
"""wstring_at(addr[, size]) -> string
|
| 529 |
+
|
| 530 |
+
Return the string at addr."""
|
| 531 |
+
return _wstring_at(ptr, size)
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
if _os.name == "nt": # COM stuff
|
| 535 |
+
def DllGetClassObject(rclsid, riid, ppv):
|
| 536 |
+
try:
|
| 537 |
+
ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
|
| 538 |
+
except ImportError:
|
| 539 |
+
return -2147221231 # CLASS_E_CLASSNOTAVAILABLE
|
| 540 |
+
else:
|
| 541 |
+
return ccom.DllGetClassObject(rclsid, riid, ppv)
|
| 542 |
+
|
| 543 |
+
def DllCanUnloadNow():
|
| 544 |
+
try:
|
| 545 |
+
ccom = __import__("comtypes.server.inprocserver", globals(), locals(), ['*'])
|
| 546 |
+
except ImportError:
|
| 547 |
+
return 0 # S_OK
|
| 548 |
+
return ccom.DllCanUnloadNow()
|
| 549 |
+
|
| 550 |
+
from ctypes._endian import BigEndianStructure, LittleEndianStructure
|
| 551 |
+
from ctypes._endian import BigEndianUnion, LittleEndianUnion
|
| 552 |
+
|
| 553 |
+
# Fill in specifically-sized types
|
| 554 |
+
c_int8 = c_byte
|
| 555 |
+
c_uint8 = c_ubyte
|
| 556 |
+
for kind in [c_short, c_int, c_long, c_longlong]:
|
| 557 |
+
if sizeof(kind) == 2: c_int16 = kind
|
| 558 |
+
elif sizeof(kind) == 4: c_int32 = kind
|
| 559 |
+
elif sizeof(kind) == 8: c_int64 = kind
|
| 560 |
+
for kind in [c_ushort, c_uint, c_ulong, c_ulonglong]:
|
| 561 |
+
if sizeof(kind) == 2: c_uint16 = kind
|
| 562 |
+
elif sizeof(kind) == 4: c_uint32 = kind
|
| 563 |
+
elif sizeof(kind) == 8: c_uint64 = kind
|
| 564 |
+
del(kind)
|
| 565 |
+
|
| 566 |
+
_reset_cache()
|
micromamba_root/envs/pytorch_env/Lib/ctypes/_aix.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Lib/ctypes.util.find_library() support for AIX
|
| 3 |
+
Similar approach as done for Darwin support by using separate files
|
| 4 |
+
but unlike Darwin - no extension such as ctypes.macholib.*
|
| 5 |
+
|
| 6 |
+
dlopen() is an interface to AIX initAndLoad() - primary documentation at:
|
| 7 |
+
https://www.ibm.com/support/knowledgecenter/en/ssw_aix_61/com.ibm.aix.basetrf1/dlopen.htm
|
| 8 |
+
https://www.ibm.com/support/knowledgecenter/en/ssw_aix_61/com.ibm.aix.basetrf1/load.htm
|
| 9 |
+
|
| 10 |
+
AIX supports two styles for dlopen(): svr4 (System V Release 4) which is common on posix
|
| 11 |
+
platforms, but also a BSD style - aka SVR3.
|
| 12 |
+
|
| 13 |
+
From AIX 5.3 Difference Addendum (December 2004)
|
| 14 |
+
2.9 SVR4 linking affinity
|
| 15 |
+
Nowadays, there are two major object file formats used by the operating systems:
|
| 16 |
+
XCOFF: The COFF enhanced by IBM and others. The original COFF (Common
|
| 17 |
+
Object File Format) was the base of SVR3 and BSD 4.2 systems.
|
| 18 |
+
ELF: Executable and Linking Format that was developed by AT&T and is a
|
| 19 |
+
base for SVR4 UNIX.
|
| 20 |
+
|
| 21 |
+
While the shared library content is identical on AIX - one is located as a filepath name
|
| 22 |
+
(svr4 style) and the other is located as a member of an archive (and the archive
|
| 23 |
+
is located as a filepath name).
|
| 24 |
+
|
| 25 |
+
The key difference arises when supporting multiple abi formats (i.e., 32 and 64 bit).
|
| 26 |
+
For svr4 either only one ABI is supported, or there are two directories, or there
|
| 27 |
+
are different file names. The most common solution for multiple ABI is multiple
|
| 28 |
+
directories.
|
| 29 |
+
|
| 30 |
+
For the XCOFF (aka AIX) style - one directory (one archive file) is sufficient
|
| 31 |
+
as multiple shared libraries can be in the archive - even sharing the same name.
|
| 32 |
+
In documentation the archive is also referred to as the "base" and the shared
|
| 33 |
+
library object is referred to as the "member".
|
| 34 |
+
|
| 35 |
+
For dlopen() on AIX (read initAndLoad()) the calls are similar.
|
| 36 |
+
Default activity occurs when no path information is provided. When path
|
| 37 |
+
information is provided dlopen() does not search any other directories.
|
| 38 |
+
|
| 39 |
+
For SVR4 - the shared library name is the name of the file expected: libFOO.so
|
| 40 |
+
For AIX - the shared library is expressed as base(member). The search is for the
|
| 41 |
+
base (e.g., libFOO.a) and once the base is found the shared library - identified by
|
| 42 |
+
member (e.g., libFOO.so, or shr.o) is located and loaded.
|
| 43 |
+
|
| 44 |
+
The mode bit RTLD_MEMBER tells initAndLoad() that it needs to use the AIX (SVR3)
|
| 45 |
+
naming style.
|
| 46 |
+
"""
|
| 47 |
+
__author__ = "Michael Felt <aixtools@felt.demon.nl>"
|
| 48 |
+
|
| 49 |
+
import re
|
| 50 |
+
from os import environ, path
|
| 51 |
+
from sys import executable
|
| 52 |
+
from ctypes import c_void_p, sizeof
|
| 53 |
+
from subprocess import Popen, PIPE, DEVNULL
|
| 54 |
+
|
| 55 |
+
# Executable bit size - 32 or 64
|
| 56 |
+
# Used to filter the search in an archive by size, e.g., -X64
|
| 57 |
+
AIX_ABI = sizeof(c_void_p) * 8
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
from sys import maxsize
|
| 61 |
+
def _last_version(libnames, sep):
|
| 62 |
+
def _num_version(libname):
|
| 63 |
+
# "libxyz.so.MAJOR.MINOR" => [MAJOR, MINOR]
|
| 64 |
+
parts = libname.split(sep)
|
| 65 |
+
nums = []
|
| 66 |
+
try:
|
| 67 |
+
while parts:
|
| 68 |
+
nums.insert(0, int(parts.pop()))
|
| 69 |
+
except ValueError:
|
| 70 |
+
pass
|
| 71 |
+
return nums or [maxsize]
|
| 72 |
+
return max(reversed(libnames), key=_num_version)
|
| 73 |
+
|
| 74 |
+
def get_ld_header(p):
|
| 75 |
+
# "nested-function, but placed at module level
|
| 76 |
+
ld_header = None
|
| 77 |
+
for line in p.stdout:
|
| 78 |
+
if line.startswith(('/', './', '../')):
|
| 79 |
+
ld_header = line
|
| 80 |
+
elif "INDEX" in line:
|
| 81 |
+
return ld_header.rstrip('\n')
|
| 82 |
+
return None
|
| 83 |
+
|
| 84 |
+
def get_ld_header_info(p):
|
| 85 |
+
# "nested-function, but placed at module level
|
| 86 |
+
# as an ld_header was found, return known paths, archives and members
|
| 87 |
+
# these lines start with a digit
|
| 88 |
+
info = []
|
| 89 |
+
for line in p.stdout:
|
| 90 |
+
if re.match("[0-9]", line):
|
| 91 |
+
info.append(line)
|
| 92 |
+
else:
|
| 93 |
+
# blank line (separator), consume line and end for loop
|
| 94 |
+
break
|
| 95 |
+
return info
|
| 96 |
+
|
| 97 |
+
def get_ld_headers(file):
|
| 98 |
+
"""
|
| 99 |
+
Parse the header of the loader section of executable and archives
|
| 100 |
+
This function calls /usr/bin/dump -H as a subprocess
|
| 101 |
+
and returns a list of (ld_header, ld_header_info) tuples.
|
| 102 |
+
"""
|
| 103 |
+
# get_ld_headers parsing:
|
| 104 |
+
# 1. Find a line that starts with /, ./, or ../ - set as ld_header
|
| 105 |
+
# 2. If "INDEX" in occurs in a following line - return ld_header
|
| 106 |
+
# 3. get info (lines starting with [0-9])
|
| 107 |
+
ldr_headers = []
|
| 108 |
+
p = Popen(["/usr/bin/dump", f"-X{AIX_ABI}", "-H", file],
|
| 109 |
+
universal_newlines=True, stdout=PIPE, stderr=DEVNULL)
|
| 110 |
+
# be sure to read to the end-of-file - getting all entries
|
| 111 |
+
while True:
|
| 112 |
+
ld_header = get_ld_header(p)
|
| 113 |
+
if ld_header:
|
| 114 |
+
ldr_headers.append((ld_header, get_ld_header_info(p)))
|
| 115 |
+
else:
|
| 116 |
+
break
|
| 117 |
+
p.stdout.close()
|
| 118 |
+
p.wait()
|
| 119 |
+
return ldr_headers
|
| 120 |
+
|
| 121 |
+
def get_shared(ld_headers):
|
| 122 |
+
"""
|
| 123 |
+
extract the shareable objects from ld_headers
|
| 124 |
+
character "[" is used to strip off the path information.
|
| 125 |
+
Note: the "[" and "]" characters that are part of dump -H output
|
| 126 |
+
are not removed here.
|
| 127 |
+
"""
|
| 128 |
+
shared = []
|
| 129 |
+
for (line, _) in ld_headers:
|
| 130 |
+
# potential member lines contain "["
|
| 131 |
+
# otherwise, no processing needed
|
| 132 |
+
if "[" in line:
|
| 133 |
+
# Strip off trailing colon (:)
|
| 134 |
+
shared.append(line[line.index("["):-1])
|
| 135 |
+
return shared
|
| 136 |
+
|
| 137 |
+
def get_one_match(expr, lines):
|
| 138 |
+
"""
|
| 139 |
+
Must be only one match, otherwise result is None.
|
| 140 |
+
When there is a match, strip leading "[" and trailing "]"
|
| 141 |
+
"""
|
| 142 |
+
# member names in the ld_headers output are between square brackets
|
| 143 |
+
expr = rf'\[({expr})\]'
|
| 144 |
+
matches = list(filter(None, (re.search(expr, line) for line in lines)))
|
| 145 |
+
if len(matches) == 1:
|
| 146 |
+
return matches[0].group(1)
|
| 147 |
+
else:
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
# additional processing to deal with AIX legacy names for 64-bit members
|
| 151 |
+
def get_legacy(members):
|
| 152 |
+
"""
|
| 153 |
+
This routine provides historical aka legacy naming schemes started
|
| 154 |
+
in AIX4 shared library support for library members names.
|
| 155 |
+
e.g., in /usr/lib/libc.a the member name shr.o for 32-bit binary and
|
| 156 |
+
shr_64.o for 64-bit binary.
|
| 157 |
+
"""
|
| 158 |
+
if AIX_ABI == 64:
|
| 159 |
+
# AIX 64-bit member is one of shr64.o, shr_64.o, or shr4_64.o
|
| 160 |
+
expr = r'shr4?_?64\.o'
|
| 161 |
+
member = get_one_match(expr, members)
|
| 162 |
+
if member:
|
| 163 |
+
return member
|
| 164 |
+
else:
|
| 165 |
+
# 32-bit legacy names - both shr.o and shr4.o exist.
|
| 166 |
+
# shr.o is the preferred name so we look for shr.o first
|
| 167 |
+
# i.e., shr4.o is returned only when shr.o does not exist
|
| 168 |
+
for name in ['shr.o', 'shr4.o']:
|
| 169 |
+
member = get_one_match(re.escape(name), members)
|
| 170 |
+
if member:
|
| 171 |
+
return member
|
| 172 |
+
return None
|
| 173 |
+
|
| 174 |
+
def get_version(name, members):
|
| 175 |
+
"""
|
| 176 |
+
Sort list of members and return highest numbered version - if it exists.
|
| 177 |
+
This function is called when an unversioned libFOO.a(libFOO.so) has
|
| 178 |
+
not been found.
|
| 179 |
+
|
| 180 |
+
Versioning for the member name is expected to follow
|
| 181 |
+
GNU LIBTOOL conventions: the highest version (x, then X.y, then X.Y.z)
|
| 182 |
+
* find [libFoo.so.X]
|
| 183 |
+
* find [libFoo.so.X.Y]
|
| 184 |
+
* find [libFoo.so.X.Y.Z]
|
| 185 |
+
|
| 186 |
+
Before the GNU convention became the standard scheme regardless of
|
| 187 |
+
binary size AIX packagers used GNU convention "as-is" for 32-bit
|
| 188 |
+
archive members but used an "distinguishing" name for 64-bit members.
|
| 189 |
+
This scheme inserted either 64 or _64 between libFOO and .so
|
| 190 |
+
- generally libFOO_64.so, but occasionally libFOO64.so
|
| 191 |
+
"""
|
| 192 |
+
# the expression ending for versions must start as
|
| 193 |
+
# '.so.[0-9]', i.e., *.so.[at least one digit]
|
| 194 |
+
# while multiple, more specific expressions could be specified
|
| 195 |
+
# to search for .so.X, .so.X.Y and .so.X.Y.Z
|
| 196 |
+
# after the first required 'dot' digit
|
| 197 |
+
# any combination of additional 'dot' digits pairs are accepted
|
| 198 |
+
# anything more than libFOO.so.digits.digits.digits
|
| 199 |
+
# should be seen as a member name outside normal expectations
|
| 200 |
+
exprs = [rf'lib{name}\.so\.[0-9]+[0-9.]*',
|
| 201 |
+
rf'lib{name}_?64\.so\.[0-9]+[0-9.]*']
|
| 202 |
+
for expr in exprs:
|
| 203 |
+
versions = []
|
| 204 |
+
for line in members:
|
| 205 |
+
m = re.search(expr, line)
|
| 206 |
+
if m:
|
| 207 |
+
versions.append(m.group(0))
|
| 208 |
+
if versions:
|
| 209 |
+
return _last_version(versions, '.')
|
| 210 |
+
return None
|
| 211 |
+
|
| 212 |
+
def get_member(name, members):
|
| 213 |
+
"""
|
| 214 |
+
Return an archive member matching the request in name.
|
| 215 |
+
Name is the library name without any prefix like lib, suffix like .so,
|
| 216 |
+
or version number.
|
| 217 |
+
Given a list of members find and return the most appropriate result
|
| 218 |
+
Priority is given to generic libXXX.so, then a versioned libXXX.so.a.b.c
|
| 219 |
+
and finally, legacy AIX naming scheme.
|
| 220 |
+
"""
|
| 221 |
+
# look first for a generic match - prepend lib and append .so
|
| 222 |
+
expr = rf'lib{name}\.so'
|
| 223 |
+
member = get_one_match(expr, members)
|
| 224 |
+
if member:
|
| 225 |
+
return member
|
| 226 |
+
elif AIX_ABI == 64:
|
| 227 |
+
expr = rf'lib{name}64\.so'
|
| 228 |
+
member = get_one_match(expr, members)
|
| 229 |
+
if member:
|
| 230 |
+
return member
|
| 231 |
+
# since an exact match with .so as suffix was not found
|
| 232 |
+
# look for a versioned name
|
| 233 |
+
# If a versioned name is not found, look for AIX legacy member name
|
| 234 |
+
member = get_version(name, members)
|
| 235 |
+
if member:
|
| 236 |
+
return member
|
| 237 |
+
else:
|
| 238 |
+
return get_legacy(members)
|
| 239 |
+
|
| 240 |
+
def get_libpaths():
|
| 241 |
+
"""
|
| 242 |
+
On AIX, the buildtime searchpath is stored in the executable.
|
| 243 |
+
as "loader header information".
|
| 244 |
+
The command /usr/bin/dump -H extracts this info.
|
| 245 |
+
Prefix searched libraries with LD_LIBRARY_PATH (preferred),
|
| 246 |
+
or LIBPATH if defined. These paths are appended to the paths
|
| 247 |
+
to libraries the python executable is linked with.
|
| 248 |
+
This mimics AIX dlopen() behavior.
|
| 249 |
+
"""
|
| 250 |
+
libpaths = environ.get("LD_LIBRARY_PATH")
|
| 251 |
+
if libpaths is None:
|
| 252 |
+
libpaths = environ.get("LIBPATH")
|
| 253 |
+
if libpaths is None:
|
| 254 |
+
libpaths = []
|
| 255 |
+
else:
|
| 256 |
+
libpaths = libpaths.split(":")
|
| 257 |
+
objects = get_ld_headers(executable)
|
| 258 |
+
for (_, lines) in objects:
|
| 259 |
+
for line in lines:
|
| 260 |
+
# the second (optional) argument is PATH if it includes a /
|
| 261 |
+
path = line.split()[1]
|
| 262 |
+
if "/" in path:
|
| 263 |
+
libpaths.extend(path.split(":"))
|
| 264 |
+
return libpaths
|
| 265 |
+
|
| 266 |
+
def find_shared(paths, name):
|
| 267 |
+
"""
|
| 268 |
+
paths is a list of directories to search for an archive.
|
| 269 |
+
name is the abbreviated name given to find_library().
|
| 270 |
+
Process: search "paths" for archive, and if an archive is found
|
| 271 |
+
return the result of get_member().
|
| 272 |
+
If an archive is not found then return None
|
| 273 |
+
"""
|
| 274 |
+
for dir in paths:
|
| 275 |
+
# /lib is a symbolic link to /usr/lib, skip it
|
| 276 |
+
if dir == "/lib":
|
| 277 |
+
continue
|
| 278 |
+
# "lib" is prefixed to emulate compiler name resolution,
|
| 279 |
+
# e.g., -lc to libc
|
| 280 |
+
base = f'lib{name}.a'
|
| 281 |
+
archive = path.join(dir, base)
|
| 282 |
+
if path.exists(archive):
|
| 283 |
+
members = get_shared(get_ld_headers(archive))
|
| 284 |
+
member = get_member(re.escape(name), members)
|
| 285 |
+
if member is not None:
|
| 286 |
+
return (base, member)
|
| 287 |
+
else:
|
| 288 |
+
return (None, None)
|
| 289 |
+
return (None, None)
|
| 290 |
+
|
| 291 |
+
def find_library(name):
|
| 292 |
+
"""AIX implementation of ctypes.util.find_library()
|
| 293 |
+
Find an archive member that will dlopen(). If not available,
|
| 294 |
+
also search for a file (or link) with a .so suffix.
|
| 295 |
+
|
| 296 |
+
AIX supports two types of schemes that can be used with dlopen().
|
| 297 |
+
The so-called SystemV Release4 (svr4) format is commonly suffixed
|
| 298 |
+
with .so while the (default) AIX scheme has the library (archive)
|
| 299 |
+
ending with the suffix .a
|
| 300 |
+
As an archive has multiple members (e.g., 32-bit and 64-bit) in one file
|
| 301 |
+
the argument passed to dlopen must include both the library and
|
| 302 |
+
the member names in a single string.
|
| 303 |
+
|
| 304 |
+
find_library() looks first for an archive (.a) with a suitable member.
|
| 305 |
+
If no archive+member pair is found, look for a .so file.
|
| 306 |
+
"""
|
| 307 |
+
|
| 308 |
+
libpaths = get_libpaths()
|
| 309 |
+
(base, member) = find_shared(libpaths, name)
|
| 310 |
+
if base is not None:
|
| 311 |
+
return f"{base}({member})"
|
| 312 |
+
|
| 313 |
+
# To get here, a member in an archive has not been found
|
| 314 |
+
# In other words, either:
|
| 315 |
+
# a) a .a file was not found
|
| 316 |
+
# b) a .a file did not have a suitable member
|
| 317 |
+
# So, look for a .so file
|
| 318 |
+
# Check libpaths for .so file
|
| 319 |
+
# Note, the installation must prepare a link from a .so
|
| 320 |
+
# to a versioned file
|
| 321 |
+
# This is common practice by GNU libtool on other platforms
|
| 322 |
+
soname = f"lib{name}.so"
|
| 323 |
+
for dir in libpaths:
|
| 324 |
+
# /lib is a symbolic link to /usr/lib, skip it
|
| 325 |
+
if dir == "/lib":
|
| 326 |
+
continue
|
| 327 |
+
shlib = path.join(dir, soname)
|
| 328 |
+
if path.exists(shlib):
|
| 329 |
+
return soname
|
| 330 |
+
# if we are here, we have not found anything plausible
|
| 331 |
+
return None
|
micromamba_root/envs/pytorch_env/Lib/ctypes/_endian.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from ctypes import *
|
| 3 |
+
|
| 4 |
+
_array_type = type(Array)
|
| 5 |
+
|
| 6 |
+
def _other_endian(typ):
|
| 7 |
+
"""Return the type with the 'other' byte order. Simple types like
|
| 8 |
+
c_int and so on already have __ctype_be__ and __ctype_le__
|
| 9 |
+
attributes which contain the types, for more complicated types
|
| 10 |
+
arrays and structures are supported.
|
| 11 |
+
"""
|
| 12 |
+
# check _OTHER_ENDIAN attribute (present if typ is primitive type)
|
| 13 |
+
if hasattr(typ, _OTHER_ENDIAN):
|
| 14 |
+
return getattr(typ, _OTHER_ENDIAN)
|
| 15 |
+
# if typ is array
|
| 16 |
+
if isinstance(typ, _array_type):
|
| 17 |
+
return _other_endian(typ._type_) * typ._length_
|
| 18 |
+
# if typ is structure or union
|
| 19 |
+
if issubclass(typ, (Structure, Union)):
|
| 20 |
+
return typ
|
| 21 |
+
raise TypeError("This type does not support other endian: %s" % typ)
|
| 22 |
+
|
| 23 |
+
class _swapped_meta:
|
| 24 |
+
def __setattr__(self, attrname, value):
|
| 25 |
+
if attrname == "_fields_":
|
| 26 |
+
fields = []
|
| 27 |
+
for desc in value:
|
| 28 |
+
name = desc[0]
|
| 29 |
+
typ = desc[1]
|
| 30 |
+
rest = desc[2:]
|
| 31 |
+
fields.append((name, _other_endian(typ)) + rest)
|
| 32 |
+
value = fields
|
| 33 |
+
super().__setattr__(attrname, value)
|
| 34 |
+
class _swapped_struct_meta(_swapped_meta, type(Structure)): pass
|
| 35 |
+
class _swapped_union_meta(_swapped_meta, type(Union)): pass
|
| 36 |
+
|
| 37 |
+
################################################################
|
| 38 |
+
|
| 39 |
+
# Note: The Structure metaclass checks for the *presence* (not the
|
| 40 |
+
# value!) of a _swapped_bytes_ attribute to determine the bit order in
|
| 41 |
+
# structures containing bit fields.
|
| 42 |
+
|
| 43 |
+
if sys.byteorder == "little":
|
| 44 |
+
_OTHER_ENDIAN = "__ctype_be__"
|
| 45 |
+
|
| 46 |
+
LittleEndianStructure = Structure
|
| 47 |
+
|
| 48 |
+
class BigEndianStructure(Structure, metaclass=_swapped_struct_meta):
|
| 49 |
+
"""Structure with big endian byte order"""
|
| 50 |
+
__slots__ = ()
|
| 51 |
+
_swappedbytes_ = None
|
| 52 |
+
|
| 53 |
+
LittleEndianUnion = Union
|
| 54 |
+
|
| 55 |
+
class BigEndianUnion(Union, metaclass=_swapped_union_meta):
|
| 56 |
+
"""Union with big endian byte order"""
|
| 57 |
+
__slots__ = ()
|
| 58 |
+
_swappedbytes_ = None
|
| 59 |
+
|
| 60 |
+
elif sys.byteorder == "big":
|
| 61 |
+
_OTHER_ENDIAN = "__ctype_le__"
|
| 62 |
+
|
| 63 |
+
BigEndianStructure = Structure
|
| 64 |
+
|
| 65 |
+
class LittleEndianStructure(Structure, metaclass=_swapped_struct_meta):
|
| 66 |
+
"""Structure with little endian byte order"""
|
| 67 |
+
__slots__ = ()
|
| 68 |
+
_swappedbytes_ = None
|
| 69 |
+
|
| 70 |
+
BigEndianUnion = Union
|
| 71 |
+
|
| 72 |
+
class LittleEndianUnion(Union, metaclass=_swapped_union_meta):
|
| 73 |
+
"""Union with little endian byte order"""
|
| 74 |
+
__slots__ = ()
|
| 75 |
+
_swappedbytes_ = None
|
| 76 |
+
|
| 77 |
+
else:
|
| 78 |
+
raise RuntimeError("Invalid byteorder")
|
micromamba_root/envs/pytorch_env/Lib/ctypes/util.py
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
import subprocess
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
# find_library(name) returns the pathname of a library, or None.
|
| 7 |
+
if os.name == "nt":
|
| 8 |
+
|
| 9 |
+
def _get_build_version():
|
| 10 |
+
"""Return the version of MSVC that was used to build Python.
|
| 11 |
+
|
| 12 |
+
For Python 2.3 and up, the version number is included in
|
| 13 |
+
sys.version. For earlier versions, assume the compiler is MSVC 6.
|
| 14 |
+
"""
|
| 15 |
+
# This function was copied from Lib/distutils/msvccompiler.py
|
| 16 |
+
prefix = "MSC v."
|
| 17 |
+
i = sys.version.find(prefix)
|
| 18 |
+
if i == -1:
|
| 19 |
+
return 6
|
| 20 |
+
i = i + len(prefix)
|
| 21 |
+
s, rest = sys.version[i:].split(" ", 1)
|
| 22 |
+
majorVersion = int(s[:-2]) - 6
|
| 23 |
+
if majorVersion >= 13:
|
| 24 |
+
majorVersion += 1
|
| 25 |
+
minorVersion = int(s[2:3]) / 10.0
|
| 26 |
+
# I don't think paths are affected by minor version in version 6
|
| 27 |
+
if majorVersion == 6:
|
| 28 |
+
minorVersion = 0
|
| 29 |
+
if majorVersion >= 6:
|
| 30 |
+
return majorVersion + minorVersion
|
| 31 |
+
# else we don't know what version of the compiler this is
|
| 32 |
+
return None
|
| 33 |
+
|
| 34 |
+
def find_msvcrt():
|
| 35 |
+
"""Return the name of the VC runtime dll"""
|
| 36 |
+
version = _get_build_version()
|
| 37 |
+
if version is None:
|
| 38 |
+
# better be safe than sorry
|
| 39 |
+
return None
|
| 40 |
+
if version <= 6:
|
| 41 |
+
clibname = 'msvcrt'
|
| 42 |
+
elif version <= 13:
|
| 43 |
+
clibname = 'msvcr%d' % (version * 10)
|
| 44 |
+
else:
|
| 45 |
+
# CRT is no longer directly loadable. See issue23606 for the
|
| 46 |
+
# discussion about alternative approaches.
|
| 47 |
+
return None
|
| 48 |
+
|
| 49 |
+
# If python was built with in debug mode
|
| 50 |
+
import importlib.machinery
|
| 51 |
+
if '_d.pyd' in importlib.machinery.EXTENSION_SUFFIXES:
|
| 52 |
+
clibname += 'd'
|
| 53 |
+
return clibname+'.dll'
|
| 54 |
+
|
| 55 |
+
def find_library(name):
|
| 56 |
+
if name in ('c', 'm'):
|
| 57 |
+
return find_msvcrt()
|
| 58 |
+
# See MSDN for the REAL search order.
|
| 59 |
+
for directory in os.environ['PATH'].split(os.pathsep):
|
| 60 |
+
fname = os.path.join(directory, name)
|
| 61 |
+
if os.path.isfile(fname):
|
| 62 |
+
return fname
|
| 63 |
+
if fname.lower().endswith(".dll"):
|
| 64 |
+
continue
|
| 65 |
+
fname = fname + ".dll"
|
| 66 |
+
if os.path.isfile(fname):
|
| 67 |
+
return fname
|
| 68 |
+
return None
|
| 69 |
+
|
| 70 |
+
elif os.name == "posix" and sys.platform == "darwin":
|
| 71 |
+
from ctypes.macholib.dyld import dyld_find as _dyld_find
|
| 72 |
+
def find_library(name):
|
| 73 |
+
possible = ['@executable_path/../lib/lib%s.dylib' % name,
|
| 74 |
+
'lib%s.dylib' % name,
|
| 75 |
+
'%s.dylib' % name,
|
| 76 |
+
'%s.framework/%s' % (name, name)]
|
| 77 |
+
for name in possible:
|
| 78 |
+
try:
|
| 79 |
+
return _dyld_find(name)
|
| 80 |
+
except ValueError:
|
| 81 |
+
continue
|
| 82 |
+
return None
|
| 83 |
+
|
| 84 |
+
elif sys.platform.startswith("aix"):
|
| 85 |
+
# AIX has two styles of storing shared libraries
|
| 86 |
+
# GNU auto_tools refer to these as svr4 and aix
|
| 87 |
+
# svr4 (System V Release 4) is a regular file, often with .so as suffix
|
| 88 |
+
# AIX style uses an archive (suffix .a) with members (e.g., shr.o, libssl.so)
|
| 89 |
+
# see issue#26439 and _aix.py for more details
|
| 90 |
+
|
| 91 |
+
from ctypes._aix import find_library
|
| 92 |
+
|
| 93 |
+
elif os.name == "posix":
|
| 94 |
+
# Andreas Degert's find functions, using gcc, /sbin/ldconfig, objdump
|
| 95 |
+
import re, tempfile
|
| 96 |
+
|
| 97 |
+
def _is_elf(filename):
|
| 98 |
+
"Return True if the given file is an ELF file"
|
| 99 |
+
elf_header = b'\x7fELF'
|
| 100 |
+
try:
|
| 101 |
+
with open(filename, 'br') as thefile:
|
| 102 |
+
return thefile.read(4) == elf_header
|
| 103 |
+
except FileNotFoundError:
|
| 104 |
+
return False
|
| 105 |
+
|
| 106 |
+
def _findLib_gcc(name):
|
| 107 |
+
# Run GCC's linker with the -t (aka --trace) option and examine the
|
| 108 |
+
# library name it prints out. The GCC command will fail because we
|
| 109 |
+
# haven't supplied a proper program with main(), but that does not
|
| 110 |
+
# matter.
|
| 111 |
+
expr = os.fsencode(r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name))
|
| 112 |
+
|
| 113 |
+
c_compiler = shutil.which('gcc')
|
| 114 |
+
if not c_compiler:
|
| 115 |
+
c_compiler = shutil.which('cc')
|
| 116 |
+
if not c_compiler:
|
| 117 |
+
# No C compiler available, give up
|
| 118 |
+
return None
|
| 119 |
+
|
| 120 |
+
temp = tempfile.NamedTemporaryFile()
|
| 121 |
+
try:
|
| 122 |
+
args = [c_compiler, '-Wl,-t', '-o', temp.name, '-l' + name]
|
| 123 |
+
|
| 124 |
+
env = dict(os.environ)
|
| 125 |
+
env['LC_ALL'] = 'C'
|
| 126 |
+
env['LANG'] = 'C'
|
| 127 |
+
try:
|
| 128 |
+
proc = subprocess.Popen(args,
|
| 129 |
+
stdout=subprocess.PIPE,
|
| 130 |
+
stderr=subprocess.STDOUT,
|
| 131 |
+
env=env)
|
| 132 |
+
except OSError: # E.g. bad executable
|
| 133 |
+
return None
|
| 134 |
+
with proc:
|
| 135 |
+
trace = proc.stdout.read()
|
| 136 |
+
finally:
|
| 137 |
+
try:
|
| 138 |
+
temp.close()
|
| 139 |
+
except FileNotFoundError:
|
| 140 |
+
# Raised if the file was already removed, which is the normal
|
| 141 |
+
# behaviour of GCC if linking fails
|
| 142 |
+
pass
|
| 143 |
+
res = re.findall(expr, trace)
|
| 144 |
+
if not res:
|
| 145 |
+
return None
|
| 146 |
+
|
| 147 |
+
for file in res:
|
| 148 |
+
# Check if the given file is an elf file: gcc can report
|
| 149 |
+
# some files that are linker scripts and not actual
|
| 150 |
+
# shared objects. See bpo-41976 for more details
|
| 151 |
+
if not _is_elf(file):
|
| 152 |
+
continue
|
| 153 |
+
return os.fsdecode(file)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if sys.platform == "sunos5":
|
| 157 |
+
# use /usr/ccs/bin/dump on solaris
|
| 158 |
+
def _get_soname(f):
|
| 159 |
+
if not f:
|
| 160 |
+
return None
|
| 161 |
+
|
| 162 |
+
try:
|
| 163 |
+
proc = subprocess.Popen(("/usr/ccs/bin/dump", "-Lpv", f),
|
| 164 |
+
stdout=subprocess.PIPE,
|
| 165 |
+
stderr=subprocess.DEVNULL)
|
| 166 |
+
except OSError: # E.g. command not found
|
| 167 |
+
return None
|
| 168 |
+
with proc:
|
| 169 |
+
data = proc.stdout.read()
|
| 170 |
+
res = re.search(br'\[.*\]\sSONAME\s+([^\s]+)', data)
|
| 171 |
+
if not res:
|
| 172 |
+
return None
|
| 173 |
+
return os.fsdecode(res.group(1))
|
| 174 |
+
else:
|
| 175 |
+
def _get_soname(f):
|
| 176 |
+
# assuming GNU binutils / ELF
|
| 177 |
+
if not f:
|
| 178 |
+
return None
|
| 179 |
+
objdump = shutil.which('objdump')
|
| 180 |
+
if not objdump:
|
| 181 |
+
# objdump is not available, give up
|
| 182 |
+
return None
|
| 183 |
+
|
| 184 |
+
try:
|
| 185 |
+
proc = subprocess.Popen((objdump, '-p', '-j', '.dynamic', f),
|
| 186 |
+
stdout=subprocess.PIPE,
|
| 187 |
+
stderr=subprocess.DEVNULL)
|
| 188 |
+
except OSError: # E.g. bad executable
|
| 189 |
+
return None
|
| 190 |
+
with proc:
|
| 191 |
+
dump = proc.stdout.read()
|
| 192 |
+
res = re.search(br'\sSONAME\s+([^\s]+)', dump)
|
| 193 |
+
if not res:
|
| 194 |
+
return None
|
| 195 |
+
return os.fsdecode(res.group(1))
|
| 196 |
+
|
| 197 |
+
if sys.platform.startswith(("freebsd", "openbsd", "dragonfly")):
|
| 198 |
+
|
| 199 |
+
def _num_version(libname):
|
| 200 |
+
# "libxyz.so.MAJOR.MINOR" => [ MAJOR, MINOR ]
|
| 201 |
+
parts = libname.split(b".")
|
| 202 |
+
nums = []
|
| 203 |
+
try:
|
| 204 |
+
while parts:
|
| 205 |
+
nums.insert(0, int(parts.pop()))
|
| 206 |
+
except ValueError:
|
| 207 |
+
pass
|
| 208 |
+
return nums or [sys.maxsize]
|
| 209 |
+
|
| 210 |
+
def find_library(name):
|
| 211 |
+
ename = re.escape(name)
|
| 212 |
+
expr = r':-l%s\.\S+ => \S*/(lib%s\.\S+)' % (ename, ename)
|
| 213 |
+
expr = os.fsencode(expr)
|
| 214 |
+
|
| 215 |
+
try:
|
| 216 |
+
proc = subprocess.Popen(('/sbin/ldconfig', '-r'),
|
| 217 |
+
stdout=subprocess.PIPE,
|
| 218 |
+
stderr=subprocess.DEVNULL)
|
| 219 |
+
except OSError: # E.g. command not found
|
| 220 |
+
data = b''
|
| 221 |
+
else:
|
| 222 |
+
with proc:
|
| 223 |
+
data = proc.stdout.read()
|
| 224 |
+
|
| 225 |
+
res = re.findall(expr, data)
|
| 226 |
+
if not res:
|
| 227 |
+
return _get_soname(_findLib_gcc(name))
|
| 228 |
+
res.sort(key=_num_version)
|
| 229 |
+
return os.fsdecode(res[-1])
|
| 230 |
+
|
| 231 |
+
elif sys.platform == "sunos5":
|
| 232 |
+
|
| 233 |
+
def _findLib_crle(name, is64):
|
| 234 |
+
if not os.path.exists('/usr/bin/crle'):
|
| 235 |
+
return None
|
| 236 |
+
|
| 237 |
+
env = dict(os.environ)
|
| 238 |
+
env['LC_ALL'] = 'C'
|
| 239 |
+
|
| 240 |
+
if is64:
|
| 241 |
+
args = ('/usr/bin/crle', '-64')
|
| 242 |
+
else:
|
| 243 |
+
args = ('/usr/bin/crle',)
|
| 244 |
+
|
| 245 |
+
paths = None
|
| 246 |
+
try:
|
| 247 |
+
proc = subprocess.Popen(args,
|
| 248 |
+
stdout=subprocess.PIPE,
|
| 249 |
+
stderr=subprocess.DEVNULL,
|
| 250 |
+
env=env)
|
| 251 |
+
except OSError: # E.g. bad executable
|
| 252 |
+
return None
|
| 253 |
+
with proc:
|
| 254 |
+
for line in proc.stdout:
|
| 255 |
+
line = line.strip()
|
| 256 |
+
if line.startswith(b'Default Library Path (ELF):'):
|
| 257 |
+
paths = os.fsdecode(line).split()[4]
|
| 258 |
+
|
| 259 |
+
if not paths:
|
| 260 |
+
return None
|
| 261 |
+
|
| 262 |
+
for dir in paths.split(":"):
|
| 263 |
+
libfile = os.path.join(dir, "lib%s.so" % name)
|
| 264 |
+
if os.path.exists(libfile):
|
| 265 |
+
return libfile
|
| 266 |
+
|
| 267 |
+
return None
|
| 268 |
+
|
| 269 |
+
def find_library(name, is64 = False):
|
| 270 |
+
return _get_soname(_findLib_crle(name, is64) or _findLib_gcc(name))
|
| 271 |
+
|
| 272 |
+
else:
|
| 273 |
+
|
| 274 |
+
def _findSoname_ldconfig(name):
|
| 275 |
+
import struct
|
| 276 |
+
if struct.calcsize('l') == 4:
|
| 277 |
+
machine = os.uname().machine + '-32'
|
| 278 |
+
else:
|
| 279 |
+
machine = os.uname().machine + '-64'
|
| 280 |
+
mach_map = {
|
| 281 |
+
'x86_64-64': 'libc6,x86-64',
|
| 282 |
+
'ppc64-64': 'libc6,64bit',
|
| 283 |
+
'sparc64-64': 'libc6,64bit',
|
| 284 |
+
's390x-64': 'libc6,64bit',
|
| 285 |
+
'ia64-64': 'libc6,IA-64',
|
| 286 |
+
}
|
| 287 |
+
abi_type = mach_map.get(machine, 'libc6')
|
| 288 |
+
|
| 289 |
+
# XXX assuming GLIBC's ldconfig (with option -p)
|
| 290 |
+
regex = r'\s+(lib%s\.[^\s]+)\s+\(%s'
|
| 291 |
+
regex = os.fsencode(regex % (re.escape(name), abi_type))
|
| 292 |
+
try:
|
| 293 |
+
with subprocess.Popen(['/sbin/ldconfig', '-p'],
|
| 294 |
+
stdin=subprocess.DEVNULL,
|
| 295 |
+
stderr=subprocess.DEVNULL,
|
| 296 |
+
stdout=subprocess.PIPE,
|
| 297 |
+
env={'LC_ALL': 'C', 'LANG': 'C'}) as p:
|
| 298 |
+
res = re.search(regex, p.stdout.read())
|
| 299 |
+
if res:
|
| 300 |
+
return os.fsdecode(res.group(1))
|
| 301 |
+
except OSError:
|
| 302 |
+
pass
|
| 303 |
+
|
| 304 |
+
def _findLib_ld(name):
|
| 305 |
+
# See issue #9998 for why this is needed
|
| 306 |
+
expr = r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name)
|
| 307 |
+
cmd = ['ld', '-t']
|
| 308 |
+
libpath = os.environ.get('LD_LIBRARY_PATH')
|
| 309 |
+
if libpath:
|
| 310 |
+
for d in libpath.split(':'):
|
| 311 |
+
cmd.extend(['-L', d])
|
| 312 |
+
cmd.extend(['-o', os.devnull, '-l%s' % name])
|
| 313 |
+
result = None
|
| 314 |
+
try:
|
| 315 |
+
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
|
| 316 |
+
stderr=subprocess.PIPE,
|
| 317 |
+
universal_newlines=True)
|
| 318 |
+
out, _ = p.communicate()
|
| 319 |
+
res = re.findall(expr, os.fsdecode(out))
|
| 320 |
+
for file in res:
|
| 321 |
+
# Check if the given file is an elf file: gcc can report
|
| 322 |
+
# some files that are linker scripts and not actual
|
| 323 |
+
# shared objects. See bpo-41976 for more details
|
| 324 |
+
if not _is_elf(file):
|
| 325 |
+
continue
|
| 326 |
+
return os.fsdecode(file)
|
| 327 |
+
except Exception:
|
| 328 |
+
pass # result will be None
|
| 329 |
+
return result
|
| 330 |
+
|
| 331 |
+
def _findLib_prefix(name):
|
| 332 |
+
if not name:
|
| 333 |
+
return None
|
| 334 |
+
for fullname in (name, "lib%s.so" % (name)):
|
| 335 |
+
path = os.path.join(sys.prefix, 'lib', fullname)
|
| 336 |
+
if os.path.exists(path) and not os.path.isdir(path):
|
| 337 |
+
return path
|
| 338 |
+
return None
|
| 339 |
+
|
| 340 |
+
def find_library(name):
|
| 341 |
+
# See issue #9998
|
| 342 |
+
# Yes calling _findLib_prefix twice is deliberate, because _get_soname ditches
|
| 343 |
+
# the full path.
|
| 344 |
+
# When objdump is unavailable this returns None
|
| 345 |
+
so_name = _get_soname(_findLib_prefix(name)) or name
|
| 346 |
+
if so_name != name:
|
| 347 |
+
return _findLib_prefix(so_name) or \
|
| 348 |
+
_findLib_prefix(name) or \
|
| 349 |
+
_findSoname_ldconfig(name) or \
|
| 350 |
+
_get_soname(_findLib_gcc(name)) or _get_soname(_findLib_ld(name))
|
| 351 |
+
else:
|
| 352 |
+
return _findLib_prefix(name) or \
|
| 353 |
+
_findSoname_ldconfig(name) or \
|
| 354 |
+
_get_soname(_findLib_gcc(name)) or _get_soname(_findLib_ld(name))
|
| 355 |
+
|
| 356 |
+
################################################################
|
| 357 |
+
# test code
|
| 358 |
+
|
| 359 |
+
def test():
|
| 360 |
+
from ctypes import cdll
|
| 361 |
+
if os.name == "nt":
|
| 362 |
+
print(cdll.msvcrt)
|
| 363 |
+
print(cdll.load("msvcrt"))
|
| 364 |
+
print(find_library("msvcrt"))
|
| 365 |
+
|
| 366 |
+
if os.name == "posix":
|
| 367 |
+
# find and load_version
|
| 368 |
+
print(find_library("m"))
|
| 369 |
+
print(find_library("c"))
|
| 370 |
+
print(find_library("bz2"))
|
| 371 |
+
|
| 372 |
+
# load
|
| 373 |
+
if sys.platform == "darwin":
|
| 374 |
+
print(cdll.LoadLibrary("libm.dylib"))
|
| 375 |
+
print(cdll.LoadLibrary("libcrypto.dylib"))
|
| 376 |
+
print(cdll.LoadLibrary("libSystem.dylib"))
|
| 377 |
+
print(cdll.LoadLibrary("System.framework/System"))
|
| 378 |
+
# issue-26439 - fix broken test call for AIX
|
| 379 |
+
elif sys.platform.startswith("aix"):
|
| 380 |
+
from ctypes import CDLL
|
| 381 |
+
if sys.maxsize < 2**32:
|
| 382 |
+
print(f"Using CDLL(name, os.RTLD_MEMBER): {CDLL('libc.a(shr.o)', os.RTLD_MEMBER)}")
|
| 383 |
+
print(f"Using cdll.LoadLibrary(): {cdll.LoadLibrary('libc.a(shr.o)')}")
|
| 384 |
+
# librpm.so is only available as 32-bit shared library
|
| 385 |
+
print(find_library("rpm"))
|
| 386 |
+
print(cdll.LoadLibrary("librpm.so"))
|
| 387 |
+
else:
|
| 388 |
+
print(f"Using CDLL(name, os.RTLD_MEMBER): {CDLL('libc.a(shr_64.o)', os.RTLD_MEMBER)}")
|
| 389 |
+
print(f"Using cdll.LoadLibrary(): {cdll.LoadLibrary('libc.a(shr_64.o)')}")
|
| 390 |
+
print(f"crypt\t:: {find_library('crypt')}")
|
| 391 |
+
print(f"crypt\t:: {cdll.LoadLibrary(find_library('crypt'))}")
|
| 392 |
+
print(f"crypto\t:: {find_library('crypto')}")
|
| 393 |
+
print(f"crypto\t:: {cdll.LoadLibrary(find_library('crypto'))}")
|
| 394 |
+
else:
|
| 395 |
+
print(cdll.LoadLibrary("libm.so"))
|
| 396 |
+
print(cdll.LoadLibrary("libcrypt.so"))
|
| 397 |
+
print(find_library("crypt"))
|
| 398 |
+
|
| 399 |
+
if __name__ == "__main__":
|
| 400 |
+
test()
|
micromamba_root/envs/pytorch_env/Lib/ctypes/wintypes.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# The most useful windows datatypes
|
| 2 |
+
import ctypes
|
| 3 |
+
|
| 4 |
+
BYTE = ctypes.c_byte
|
| 5 |
+
WORD = ctypes.c_ushort
|
| 6 |
+
DWORD = ctypes.c_ulong
|
| 7 |
+
|
| 8 |
+
#UCHAR = ctypes.c_uchar
|
| 9 |
+
CHAR = ctypes.c_char
|
| 10 |
+
WCHAR = ctypes.c_wchar
|
| 11 |
+
UINT = ctypes.c_uint
|
| 12 |
+
INT = ctypes.c_int
|
| 13 |
+
|
| 14 |
+
DOUBLE = ctypes.c_double
|
| 15 |
+
FLOAT = ctypes.c_float
|
| 16 |
+
|
| 17 |
+
BOOLEAN = BYTE
|
| 18 |
+
BOOL = ctypes.c_long
|
| 19 |
+
|
| 20 |
+
class VARIANT_BOOL(ctypes._SimpleCData):
|
| 21 |
+
_type_ = "v"
|
| 22 |
+
def __repr__(self):
|
| 23 |
+
return "%s(%r)" % (self.__class__.__name__, self.value)
|
| 24 |
+
|
| 25 |
+
ULONG = ctypes.c_ulong
|
| 26 |
+
LONG = ctypes.c_long
|
| 27 |
+
|
| 28 |
+
USHORT = ctypes.c_ushort
|
| 29 |
+
SHORT = ctypes.c_short
|
| 30 |
+
|
| 31 |
+
# in the windows header files, these are structures.
|
| 32 |
+
_LARGE_INTEGER = LARGE_INTEGER = ctypes.c_longlong
|
| 33 |
+
_ULARGE_INTEGER = ULARGE_INTEGER = ctypes.c_ulonglong
|
| 34 |
+
|
| 35 |
+
LPCOLESTR = LPOLESTR = OLESTR = ctypes.c_wchar_p
|
| 36 |
+
LPCWSTR = LPWSTR = ctypes.c_wchar_p
|
| 37 |
+
LPCSTR = LPSTR = ctypes.c_char_p
|
| 38 |
+
LPCVOID = LPVOID = ctypes.c_void_p
|
| 39 |
+
|
| 40 |
+
# WPARAM is defined as UINT_PTR (unsigned type)
|
| 41 |
+
# LPARAM is defined as LONG_PTR (signed type)
|
| 42 |
+
if ctypes.sizeof(ctypes.c_long) == ctypes.sizeof(ctypes.c_void_p):
|
| 43 |
+
WPARAM = ctypes.c_ulong
|
| 44 |
+
LPARAM = ctypes.c_long
|
| 45 |
+
elif ctypes.sizeof(ctypes.c_longlong) == ctypes.sizeof(ctypes.c_void_p):
|
| 46 |
+
WPARAM = ctypes.c_ulonglong
|
| 47 |
+
LPARAM = ctypes.c_longlong
|
| 48 |
+
|
| 49 |
+
ATOM = WORD
|
| 50 |
+
LANGID = WORD
|
| 51 |
+
|
| 52 |
+
COLORREF = DWORD
|
| 53 |
+
LGRPID = DWORD
|
| 54 |
+
LCTYPE = DWORD
|
| 55 |
+
|
| 56 |
+
LCID = DWORD
|
| 57 |
+
|
| 58 |
+
################################################################
|
| 59 |
+
# HANDLE types
|
| 60 |
+
HANDLE = ctypes.c_void_p # in the header files: void *
|
| 61 |
+
|
| 62 |
+
HACCEL = HANDLE
|
| 63 |
+
HBITMAP = HANDLE
|
| 64 |
+
HBRUSH = HANDLE
|
| 65 |
+
HCOLORSPACE = HANDLE
|
| 66 |
+
HDC = HANDLE
|
| 67 |
+
HDESK = HANDLE
|
| 68 |
+
HDWP = HANDLE
|
| 69 |
+
HENHMETAFILE = HANDLE
|
| 70 |
+
HFONT = HANDLE
|
| 71 |
+
HGDIOBJ = HANDLE
|
| 72 |
+
HGLOBAL = HANDLE
|
| 73 |
+
HHOOK = HANDLE
|
| 74 |
+
HICON = HANDLE
|
| 75 |
+
HINSTANCE = HANDLE
|
| 76 |
+
HKEY = HANDLE
|
| 77 |
+
HKL = HANDLE
|
| 78 |
+
HLOCAL = HANDLE
|
| 79 |
+
HMENU = HANDLE
|
| 80 |
+
HMETAFILE = HANDLE
|
| 81 |
+
HMODULE = HANDLE
|
| 82 |
+
HMONITOR = HANDLE
|
| 83 |
+
HPALETTE = HANDLE
|
| 84 |
+
HPEN = HANDLE
|
| 85 |
+
HRGN = HANDLE
|
| 86 |
+
HRSRC = HANDLE
|
| 87 |
+
HSTR = HANDLE
|
| 88 |
+
HTASK = HANDLE
|
| 89 |
+
HWINSTA = HANDLE
|
| 90 |
+
HWND = HANDLE
|
| 91 |
+
SC_HANDLE = HANDLE
|
| 92 |
+
SERVICE_STATUS_HANDLE = HANDLE
|
| 93 |
+
|
| 94 |
+
################################################################
|
| 95 |
+
# Some important structure definitions
|
| 96 |
+
|
| 97 |
+
class RECT(ctypes.Structure):
|
| 98 |
+
_fields_ = [("left", LONG),
|
| 99 |
+
("top", LONG),
|
| 100 |
+
("right", LONG),
|
| 101 |
+
("bottom", LONG)]
|
| 102 |
+
tagRECT = _RECTL = RECTL = RECT
|
| 103 |
+
|
| 104 |
+
class _SMALL_RECT(ctypes.Structure):
|
| 105 |
+
_fields_ = [('Left', SHORT),
|
| 106 |
+
('Top', SHORT),
|
| 107 |
+
('Right', SHORT),
|
| 108 |
+
('Bottom', SHORT)]
|
| 109 |
+
SMALL_RECT = _SMALL_RECT
|
| 110 |
+
|
| 111 |
+
class _COORD(ctypes.Structure):
|
| 112 |
+
_fields_ = [('X', SHORT),
|
| 113 |
+
('Y', SHORT)]
|
| 114 |
+
|
| 115 |
+
class POINT(ctypes.Structure):
|
| 116 |
+
_fields_ = [("x", LONG),
|
| 117 |
+
("y", LONG)]
|
| 118 |
+
tagPOINT = _POINTL = POINTL = POINT
|
| 119 |
+
|
| 120 |
+
class SIZE(ctypes.Structure):
|
| 121 |
+
_fields_ = [("cx", LONG),
|
| 122 |
+
("cy", LONG)]
|
| 123 |
+
tagSIZE = SIZEL = SIZE
|
| 124 |
+
|
| 125 |
+
def RGB(red, green, blue):
|
| 126 |
+
return red + (green << 8) + (blue << 16)
|
| 127 |
+
|
| 128 |
+
class FILETIME(ctypes.Structure):
|
| 129 |
+
_fields_ = [("dwLowDateTime", DWORD),
|
| 130 |
+
("dwHighDateTime", DWORD)]
|
| 131 |
+
_FILETIME = FILETIME
|
| 132 |
+
|
| 133 |
+
class MSG(ctypes.Structure):
|
| 134 |
+
_fields_ = [("hWnd", HWND),
|
| 135 |
+
("message", UINT),
|
| 136 |
+
("wParam", WPARAM),
|
| 137 |
+
("lParam", LPARAM),
|
| 138 |
+
("time", DWORD),
|
| 139 |
+
("pt", POINT)]
|
| 140 |
+
tagMSG = MSG
|
| 141 |
+
MAX_PATH = 260
|
| 142 |
+
|
| 143 |
+
class WIN32_FIND_DATAA(ctypes.Structure):
|
| 144 |
+
_fields_ = [("dwFileAttributes", DWORD),
|
| 145 |
+
("ftCreationTime", FILETIME),
|
| 146 |
+
("ftLastAccessTime", FILETIME),
|
| 147 |
+
("ftLastWriteTime", FILETIME),
|
| 148 |
+
("nFileSizeHigh", DWORD),
|
| 149 |
+
("nFileSizeLow", DWORD),
|
| 150 |
+
("dwReserved0", DWORD),
|
| 151 |
+
("dwReserved1", DWORD),
|
| 152 |
+
("cFileName", CHAR * MAX_PATH),
|
| 153 |
+
("cAlternateFileName", CHAR * 14)]
|
| 154 |
+
|
| 155 |
+
class WIN32_FIND_DATAW(ctypes.Structure):
|
| 156 |
+
_fields_ = [("dwFileAttributes", DWORD),
|
| 157 |
+
("ftCreationTime", FILETIME),
|
| 158 |
+
("ftLastAccessTime", FILETIME),
|
| 159 |
+
("ftLastWriteTime", FILETIME),
|
| 160 |
+
("nFileSizeHigh", DWORD),
|
| 161 |
+
("nFileSizeLow", DWORD),
|
| 162 |
+
("dwReserved0", DWORD),
|
| 163 |
+
("dwReserved1", DWORD),
|
| 164 |
+
("cFileName", WCHAR * MAX_PATH),
|
| 165 |
+
("cAlternateFileName", WCHAR * 14)]
|
| 166 |
+
|
| 167 |
+
################################################################
|
| 168 |
+
# Pointer types
|
| 169 |
+
|
| 170 |
+
LPBOOL = PBOOL = ctypes.POINTER(BOOL)
|
| 171 |
+
PBOOLEAN = ctypes.POINTER(BOOLEAN)
|
| 172 |
+
LPBYTE = PBYTE = ctypes.POINTER(BYTE)
|
| 173 |
+
PCHAR = ctypes.POINTER(CHAR)
|
| 174 |
+
LPCOLORREF = ctypes.POINTER(COLORREF)
|
| 175 |
+
LPDWORD = PDWORD = ctypes.POINTER(DWORD)
|
| 176 |
+
LPFILETIME = PFILETIME = ctypes.POINTER(FILETIME)
|
| 177 |
+
PFLOAT = ctypes.POINTER(FLOAT)
|
| 178 |
+
LPHANDLE = PHANDLE = ctypes.POINTER(HANDLE)
|
| 179 |
+
PHKEY = ctypes.POINTER(HKEY)
|
| 180 |
+
LPHKL = ctypes.POINTER(HKL)
|
| 181 |
+
LPINT = PINT = ctypes.POINTER(INT)
|
| 182 |
+
PLARGE_INTEGER = ctypes.POINTER(LARGE_INTEGER)
|
| 183 |
+
PLCID = ctypes.POINTER(LCID)
|
| 184 |
+
LPLONG = PLONG = ctypes.POINTER(LONG)
|
| 185 |
+
LPMSG = PMSG = ctypes.POINTER(MSG)
|
| 186 |
+
LPPOINT = PPOINT = ctypes.POINTER(POINT)
|
| 187 |
+
PPOINTL = ctypes.POINTER(POINTL)
|
| 188 |
+
LPRECT = PRECT = ctypes.POINTER(RECT)
|
| 189 |
+
LPRECTL = PRECTL = ctypes.POINTER(RECTL)
|
| 190 |
+
LPSC_HANDLE = ctypes.POINTER(SC_HANDLE)
|
| 191 |
+
PSHORT = ctypes.POINTER(SHORT)
|
| 192 |
+
LPSIZE = PSIZE = ctypes.POINTER(SIZE)
|
| 193 |
+
LPSIZEL = PSIZEL = ctypes.POINTER(SIZEL)
|
| 194 |
+
PSMALL_RECT = ctypes.POINTER(SMALL_RECT)
|
| 195 |
+
LPUINT = PUINT = ctypes.POINTER(UINT)
|
| 196 |
+
PULARGE_INTEGER = ctypes.POINTER(ULARGE_INTEGER)
|
| 197 |
+
PULONG = ctypes.POINTER(ULONG)
|
| 198 |
+
PUSHORT = ctypes.POINTER(USHORT)
|
| 199 |
+
PWCHAR = ctypes.POINTER(WCHAR)
|
| 200 |
+
LPWIN32_FIND_DATAA = PWIN32_FIND_DATAA = ctypes.POINTER(WIN32_FIND_DATAA)
|
| 201 |
+
LPWIN32_FIND_DATAW = PWIN32_FIND_DATAW = ctypes.POINTER(WIN32_FIND_DATAW)
|
| 202 |
+
LPWORD = PWORD = ctypes.POINTER(WORD)
|
micromamba_root/envs/pytorch_env/Lib/curses/__init__.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""curses
|
| 2 |
+
|
| 3 |
+
The main package for curses support for Python. Normally used by importing
|
| 4 |
+
the package, and perhaps a particular module inside it.
|
| 5 |
+
|
| 6 |
+
import curses
|
| 7 |
+
from curses import textpad
|
| 8 |
+
curses.initscr()
|
| 9 |
+
...
|
| 10 |
+
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from _curses import *
|
| 14 |
+
import os as _os
|
| 15 |
+
import sys as _sys
|
| 16 |
+
|
| 17 |
+
# Some constants, most notably the ACS_* ones, are only added to the C
|
| 18 |
+
# _curses module's dictionary after initscr() is called. (Some
|
| 19 |
+
# versions of SGI's curses don't define values for those constants
|
| 20 |
+
# until initscr() has been called.) This wrapper function calls the
|
| 21 |
+
# underlying C initscr(), and then copies the constants from the
|
| 22 |
+
# _curses module to the curses package's dictionary. Don't do 'from
|
| 23 |
+
# curses import *' if you'll be needing the ACS_* constants.
|
| 24 |
+
|
| 25 |
+
def initscr():
|
| 26 |
+
import _curses, curses
|
| 27 |
+
# we call setupterm() here because it raises an error
|
| 28 |
+
# instead of calling exit() in error cases.
|
| 29 |
+
setupterm(term=_os.environ.get("TERM", "unknown"),
|
| 30 |
+
fd=_sys.__stdout__.fileno())
|
| 31 |
+
stdscr = _curses.initscr()
|
| 32 |
+
for key, value in _curses.__dict__.items():
|
| 33 |
+
if key[0:4] == 'ACS_' or key in ('LINES', 'COLS'):
|
| 34 |
+
setattr(curses, key, value)
|
| 35 |
+
|
| 36 |
+
return stdscr
|
| 37 |
+
|
| 38 |
+
# This is a similar wrapper for start_color(), which adds the COLORS and
|
| 39 |
+
# COLOR_PAIRS variables which are only available after start_color() is
|
| 40 |
+
# called.
|
| 41 |
+
|
| 42 |
+
def start_color():
|
| 43 |
+
import _curses, curses
|
| 44 |
+
retval = _curses.start_color()
|
| 45 |
+
if hasattr(_curses, 'COLORS'):
|
| 46 |
+
curses.COLORS = _curses.COLORS
|
| 47 |
+
if hasattr(_curses, 'COLOR_PAIRS'):
|
| 48 |
+
curses.COLOR_PAIRS = _curses.COLOR_PAIRS
|
| 49 |
+
return retval
|
| 50 |
+
|
| 51 |
+
# Import Python has_key() implementation if _curses doesn't contain has_key()
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
has_key
|
| 55 |
+
except NameError:
|
| 56 |
+
from .has_key import has_key
|
| 57 |
+
|
| 58 |
+
# Wrapper for the entire curses-based application. Runs a function which
|
| 59 |
+
# should be the rest of your curses-based application. If the application
|
| 60 |
+
# raises an exception, wrapper() will restore the terminal to a sane state so
|
| 61 |
+
# you can read the resulting traceback.
|
| 62 |
+
|
| 63 |
+
def wrapper(func, /, *args, **kwds):
|
| 64 |
+
"""Wrapper function that initializes curses and calls another function,
|
| 65 |
+
restoring normal keyboard/screen behavior on error.
|
| 66 |
+
The callable object 'func' is then passed the main window 'stdscr'
|
| 67 |
+
as its first argument, followed by any other arguments passed to
|
| 68 |
+
wrapper().
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
try:
|
| 72 |
+
# Initialize curses
|
| 73 |
+
stdscr = initscr()
|
| 74 |
+
|
| 75 |
+
# Turn off echoing of keys, and enter cbreak mode,
|
| 76 |
+
# where no buffering is performed on keyboard input
|
| 77 |
+
noecho()
|
| 78 |
+
cbreak()
|
| 79 |
+
|
| 80 |
+
# In keypad mode, escape sequences for special keys
|
| 81 |
+
# (like the cursor keys) will be interpreted and
|
| 82 |
+
# a special value like curses.KEY_LEFT will be returned
|
| 83 |
+
stdscr.keypad(1)
|
| 84 |
+
|
| 85 |
+
# Start color, too. Harmless if the terminal doesn't have
|
| 86 |
+
# color; user can test with has_color() later on. The try/catch
|
| 87 |
+
# works around a minor bit of over-conscientiousness in the curses
|
| 88 |
+
# module -- the error return from C start_color() is ignorable.
|
| 89 |
+
try:
|
| 90 |
+
start_color()
|
| 91 |
+
except:
|
| 92 |
+
pass
|
| 93 |
+
|
| 94 |
+
return func(stdscr, *args, **kwds)
|
| 95 |
+
finally:
|
| 96 |
+
# Set everything back to normal
|
| 97 |
+
if 'stdscr' in locals():
|
| 98 |
+
stdscr.keypad(0)
|
| 99 |
+
echo()
|
| 100 |
+
nocbreak()
|
| 101 |
+
endwin()
|
micromamba_root/envs/pytorch_env/Lib/curses/ascii.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Constants and membership tests for ASCII characters"""
|
| 2 |
+
|
| 3 |
+
NUL = 0x00 # ^@
|
| 4 |
+
SOH = 0x01 # ^A
|
| 5 |
+
STX = 0x02 # ^B
|
| 6 |
+
ETX = 0x03 # ^C
|
| 7 |
+
EOT = 0x04 # ^D
|
| 8 |
+
ENQ = 0x05 # ^E
|
| 9 |
+
ACK = 0x06 # ^F
|
| 10 |
+
BEL = 0x07 # ^G
|
| 11 |
+
BS = 0x08 # ^H
|
| 12 |
+
TAB = 0x09 # ^I
|
| 13 |
+
HT = 0x09 # ^I
|
| 14 |
+
LF = 0x0a # ^J
|
| 15 |
+
NL = 0x0a # ^J
|
| 16 |
+
VT = 0x0b # ^K
|
| 17 |
+
FF = 0x0c # ^L
|
| 18 |
+
CR = 0x0d # ^M
|
| 19 |
+
SO = 0x0e # ^N
|
| 20 |
+
SI = 0x0f # ^O
|
| 21 |
+
DLE = 0x10 # ^P
|
| 22 |
+
DC1 = 0x11 # ^Q
|
| 23 |
+
DC2 = 0x12 # ^R
|
| 24 |
+
DC3 = 0x13 # ^S
|
| 25 |
+
DC4 = 0x14 # ^T
|
| 26 |
+
NAK = 0x15 # ^U
|
| 27 |
+
SYN = 0x16 # ^V
|
| 28 |
+
ETB = 0x17 # ^W
|
| 29 |
+
CAN = 0x18 # ^X
|
| 30 |
+
EM = 0x19 # ^Y
|
| 31 |
+
SUB = 0x1a # ^Z
|
| 32 |
+
ESC = 0x1b # ^[
|
| 33 |
+
FS = 0x1c # ^\
|
| 34 |
+
GS = 0x1d # ^]
|
| 35 |
+
RS = 0x1e # ^^
|
| 36 |
+
US = 0x1f # ^_
|
| 37 |
+
SP = 0x20 # space
|
| 38 |
+
DEL = 0x7f # delete
|
| 39 |
+
|
| 40 |
+
controlnames = [
|
| 41 |
+
"NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL",
|
| 42 |
+
"BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI",
|
| 43 |
+
"DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB",
|
| 44 |
+
"CAN", "EM", "SUB", "ESC", "FS", "GS", "RS", "US",
|
| 45 |
+
"SP"
|
| 46 |
+
]
|
| 47 |
+
|
| 48 |
+
def _ctoi(c):
|
| 49 |
+
if type(c) == type(""):
|
| 50 |
+
return ord(c)
|
| 51 |
+
else:
|
| 52 |
+
return c
|
| 53 |
+
|
| 54 |
+
def isalnum(c): return isalpha(c) or isdigit(c)
|
| 55 |
+
def isalpha(c): return isupper(c) or islower(c)
|
| 56 |
+
def isascii(c): return 0 <= _ctoi(c) <= 127 # ?
|
| 57 |
+
def isblank(c): return _ctoi(c) in (9, 32)
|
| 58 |
+
def iscntrl(c): return 0 <= _ctoi(c) <= 31 or _ctoi(c) == 127
|
| 59 |
+
def isdigit(c): return 48 <= _ctoi(c) <= 57
|
| 60 |
+
def isgraph(c): return 33 <= _ctoi(c) <= 126
|
| 61 |
+
def islower(c): return 97 <= _ctoi(c) <= 122
|
| 62 |
+
def isprint(c): return 32 <= _ctoi(c) <= 126
|
| 63 |
+
def ispunct(c): return isgraph(c) and not isalnum(c)
|
| 64 |
+
def isspace(c): return _ctoi(c) in (9, 10, 11, 12, 13, 32)
|
| 65 |
+
def isupper(c): return 65 <= _ctoi(c) <= 90
|
| 66 |
+
def isxdigit(c): return isdigit(c) or \
|
| 67 |
+
(65 <= _ctoi(c) <= 70) or (97 <= _ctoi(c) <= 102)
|
| 68 |
+
def isctrl(c): return 0 <= _ctoi(c) < 32
|
| 69 |
+
def ismeta(c): return _ctoi(c) > 127
|
| 70 |
+
|
| 71 |
+
def ascii(c):
|
| 72 |
+
if type(c) == type(""):
|
| 73 |
+
return chr(_ctoi(c) & 0x7f)
|
| 74 |
+
else:
|
| 75 |
+
return _ctoi(c) & 0x7f
|
| 76 |
+
|
| 77 |
+
def ctrl(c):
|
| 78 |
+
if type(c) == type(""):
|
| 79 |
+
return chr(_ctoi(c) & 0x1f)
|
| 80 |
+
else:
|
| 81 |
+
return _ctoi(c) & 0x1f
|
| 82 |
+
|
| 83 |
+
def alt(c):
|
| 84 |
+
if type(c) == type(""):
|
| 85 |
+
return chr(_ctoi(c) | 0x80)
|
| 86 |
+
else:
|
| 87 |
+
return _ctoi(c) | 0x80
|
| 88 |
+
|
| 89 |
+
def unctrl(c):
|
| 90 |
+
bits = _ctoi(c)
|
| 91 |
+
if bits == 0x7f:
|
| 92 |
+
rep = "^?"
|
| 93 |
+
elif isprint(bits & 0x7f):
|
| 94 |
+
rep = chr(bits & 0x7f)
|
| 95 |
+
else:
|
| 96 |
+
rep = "^" + chr(((bits & 0x7f) | 0x20) + 0x20)
|
| 97 |
+
if bits & 0x80:
|
| 98 |
+
return "!" + rep
|
| 99 |
+
return rep
|
micromamba_root/envs/pytorch_env/Lib/curses/has_key.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
#
|
| 3 |
+
# Emulation of has_key() function for platforms that don't use ncurses
|
| 4 |
+
#
|
| 5 |
+
|
| 6 |
+
import _curses
|
| 7 |
+
|
| 8 |
+
# Table mapping curses keys to the terminfo capability name
|
| 9 |
+
|
| 10 |
+
_capability_names = {
|
| 11 |
+
_curses.KEY_A1: 'ka1',
|
| 12 |
+
_curses.KEY_A3: 'ka3',
|
| 13 |
+
_curses.KEY_B2: 'kb2',
|
| 14 |
+
_curses.KEY_BACKSPACE: 'kbs',
|
| 15 |
+
_curses.KEY_BEG: 'kbeg',
|
| 16 |
+
_curses.KEY_BTAB: 'kcbt',
|
| 17 |
+
_curses.KEY_C1: 'kc1',
|
| 18 |
+
_curses.KEY_C3: 'kc3',
|
| 19 |
+
_curses.KEY_CANCEL: 'kcan',
|
| 20 |
+
_curses.KEY_CATAB: 'ktbc',
|
| 21 |
+
_curses.KEY_CLEAR: 'kclr',
|
| 22 |
+
_curses.KEY_CLOSE: 'kclo',
|
| 23 |
+
_curses.KEY_COMMAND: 'kcmd',
|
| 24 |
+
_curses.KEY_COPY: 'kcpy',
|
| 25 |
+
_curses.KEY_CREATE: 'kcrt',
|
| 26 |
+
_curses.KEY_CTAB: 'kctab',
|
| 27 |
+
_curses.KEY_DC: 'kdch1',
|
| 28 |
+
_curses.KEY_DL: 'kdl1',
|
| 29 |
+
_curses.KEY_DOWN: 'kcud1',
|
| 30 |
+
_curses.KEY_EIC: 'krmir',
|
| 31 |
+
_curses.KEY_END: 'kend',
|
| 32 |
+
_curses.KEY_ENTER: 'kent',
|
| 33 |
+
_curses.KEY_EOL: 'kel',
|
| 34 |
+
_curses.KEY_EOS: 'ked',
|
| 35 |
+
_curses.KEY_EXIT: 'kext',
|
| 36 |
+
_curses.KEY_F0: 'kf0',
|
| 37 |
+
_curses.KEY_F1: 'kf1',
|
| 38 |
+
_curses.KEY_F10: 'kf10',
|
| 39 |
+
_curses.KEY_F11: 'kf11',
|
| 40 |
+
_curses.KEY_F12: 'kf12',
|
| 41 |
+
_curses.KEY_F13: 'kf13',
|
| 42 |
+
_curses.KEY_F14: 'kf14',
|
| 43 |
+
_curses.KEY_F15: 'kf15',
|
| 44 |
+
_curses.KEY_F16: 'kf16',
|
| 45 |
+
_curses.KEY_F17: 'kf17',
|
| 46 |
+
_curses.KEY_F18: 'kf18',
|
| 47 |
+
_curses.KEY_F19: 'kf19',
|
| 48 |
+
_curses.KEY_F2: 'kf2',
|
| 49 |
+
_curses.KEY_F20: 'kf20',
|
| 50 |
+
_curses.KEY_F21: 'kf21',
|
| 51 |
+
_curses.KEY_F22: 'kf22',
|
| 52 |
+
_curses.KEY_F23: 'kf23',
|
| 53 |
+
_curses.KEY_F24: 'kf24',
|
| 54 |
+
_curses.KEY_F25: 'kf25',
|
| 55 |
+
_curses.KEY_F26: 'kf26',
|
| 56 |
+
_curses.KEY_F27: 'kf27',
|
| 57 |
+
_curses.KEY_F28: 'kf28',
|
| 58 |
+
_curses.KEY_F29: 'kf29',
|
| 59 |
+
_curses.KEY_F3: 'kf3',
|
| 60 |
+
_curses.KEY_F30: 'kf30',
|
| 61 |
+
_curses.KEY_F31: 'kf31',
|
| 62 |
+
_curses.KEY_F32: 'kf32',
|
| 63 |
+
_curses.KEY_F33: 'kf33',
|
| 64 |
+
_curses.KEY_F34: 'kf34',
|
| 65 |
+
_curses.KEY_F35: 'kf35',
|
| 66 |
+
_curses.KEY_F36: 'kf36',
|
| 67 |
+
_curses.KEY_F37: 'kf37',
|
| 68 |
+
_curses.KEY_F38: 'kf38',
|
| 69 |
+
_curses.KEY_F39: 'kf39',
|
| 70 |
+
_curses.KEY_F4: 'kf4',
|
| 71 |
+
_curses.KEY_F40: 'kf40',
|
| 72 |
+
_curses.KEY_F41: 'kf41',
|
| 73 |
+
_curses.KEY_F42: 'kf42',
|
| 74 |
+
_curses.KEY_F43: 'kf43',
|
| 75 |
+
_curses.KEY_F44: 'kf44',
|
| 76 |
+
_curses.KEY_F45: 'kf45',
|
| 77 |
+
_curses.KEY_F46: 'kf46',
|
| 78 |
+
_curses.KEY_F47: 'kf47',
|
| 79 |
+
_curses.KEY_F48: 'kf48',
|
| 80 |
+
_curses.KEY_F49: 'kf49',
|
| 81 |
+
_curses.KEY_F5: 'kf5',
|
| 82 |
+
_curses.KEY_F50: 'kf50',
|
| 83 |
+
_curses.KEY_F51: 'kf51',
|
| 84 |
+
_curses.KEY_F52: 'kf52',
|
| 85 |
+
_curses.KEY_F53: 'kf53',
|
| 86 |
+
_curses.KEY_F54: 'kf54',
|
| 87 |
+
_curses.KEY_F55: 'kf55',
|
| 88 |
+
_curses.KEY_F56: 'kf56',
|
| 89 |
+
_curses.KEY_F57: 'kf57',
|
| 90 |
+
_curses.KEY_F58: 'kf58',
|
| 91 |
+
_curses.KEY_F59: 'kf59',
|
| 92 |
+
_curses.KEY_F6: 'kf6',
|
| 93 |
+
_curses.KEY_F60: 'kf60',
|
| 94 |
+
_curses.KEY_F61: 'kf61',
|
| 95 |
+
_curses.KEY_F62: 'kf62',
|
| 96 |
+
_curses.KEY_F63: 'kf63',
|
| 97 |
+
_curses.KEY_F7: 'kf7',
|
| 98 |
+
_curses.KEY_F8: 'kf8',
|
| 99 |
+
_curses.KEY_F9: 'kf9',
|
| 100 |
+
_curses.KEY_FIND: 'kfnd',
|
| 101 |
+
_curses.KEY_HELP: 'khlp',
|
| 102 |
+
_curses.KEY_HOME: 'khome',
|
| 103 |
+
_curses.KEY_IC: 'kich1',
|
| 104 |
+
_curses.KEY_IL: 'kil1',
|
| 105 |
+
_curses.KEY_LEFT: 'kcub1',
|
| 106 |
+
_curses.KEY_LL: 'kll',
|
| 107 |
+
_curses.KEY_MARK: 'kmrk',
|
| 108 |
+
_curses.KEY_MESSAGE: 'kmsg',
|
| 109 |
+
_curses.KEY_MOVE: 'kmov',
|
| 110 |
+
_curses.KEY_NEXT: 'knxt',
|
| 111 |
+
_curses.KEY_NPAGE: 'knp',
|
| 112 |
+
_curses.KEY_OPEN: 'kopn',
|
| 113 |
+
_curses.KEY_OPTIONS: 'kopt',
|
| 114 |
+
_curses.KEY_PPAGE: 'kpp',
|
| 115 |
+
_curses.KEY_PREVIOUS: 'kprv',
|
| 116 |
+
_curses.KEY_PRINT: 'kprt',
|
| 117 |
+
_curses.KEY_REDO: 'krdo',
|
| 118 |
+
_curses.KEY_REFERENCE: 'kref',
|
| 119 |
+
_curses.KEY_REFRESH: 'krfr',
|
| 120 |
+
_curses.KEY_REPLACE: 'krpl',
|
| 121 |
+
_curses.KEY_RESTART: 'krst',
|
| 122 |
+
_curses.KEY_RESUME: 'kres',
|
| 123 |
+
_curses.KEY_RIGHT: 'kcuf1',
|
| 124 |
+
_curses.KEY_SAVE: 'ksav',
|
| 125 |
+
_curses.KEY_SBEG: 'kBEG',
|
| 126 |
+
_curses.KEY_SCANCEL: 'kCAN',
|
| 127 |
+
_curses.KEY_SCOMMAND: 'kCMD',
|
| 128 |
+
_curses.KEY_SCOPY: 'kCPY',
|
| 129 |
+
_curses.KEY_SCREATE: 'kCRT',
|
| 130 |
+
_curses.KEY_SDC: 'kDC',
|
| 131 |
+
_curses.KEY_SDL: 'kDL',
|
| 132 |
+
_curses.KEY_SELECT: 'kslt',
|
| 133 |
+
_curses.KEY_SEND: 'kEND',
|
| 134 |
+
_curses.KEY_SEOL: 'kEOL',
|
| 135 |
+
_curses.KEY_SEXIT: 'kEXT',
|
| 136 |
+
_curses.KEY_SF: 'kind',
|
| 137 |
+
_curses.KEY_SFIND: 'kFND',
|
| 138 |
+
_curses.KEY_SHELP: 'kHLP',
|
| 139 |
+
_curses.KEY_SHOME: 'kHOM',
|
| 140 |
+
_curses.KEY_SIC: 'kIC',
|
| 141 |
+
_curses.KEY_SLEFT: 'kLFT',
|
| 142 |
+
_curses.KEY_SMESSAGE: 'kMSG',
|
| 143 |
+
_curses.KEY_SMOVE: 'kMOV',
|
| 144 |
+
_curses.KEY_SNEXT: 'kNXT',
|
| 145 |
+
_curses.KEY_SOPTIONS: 'kOPT',
|
| 146 |
+
_curses.KEY_SPREVIOUS: 'kPRV',
|
| 147 |
+
_curses.KEY_SPRINT: 'kPRT',
|
| 148 |
+
_curses.KEY_SR: 'kri',
|
| 149 |
+
_curses.KEY_SREDO: 'kRDO',
|
| 150 |
+
_curses.KEY_SREPLACE: 'kRPL',
|
| 151 |
+
_curses.KEY_SRIGHT: 'kRIT',
|
| 152 |
+
_curses.KEY_SRSUME: 'kRES',
|
| 153 |
+
_curses.KEY_SSAVE: 'kSAV',
|
| 154 |
+
_curses.KEY_SSUSPEND: 'kSPD',
|
| 155 |
+
_curses.KEY_STAB: 'khts',
|
| 156 |
+
_curses.KEY_SUNDO: 'kUND',
|
| 157 |
+
_curses.KEY_SUSPEND: 'kspd',
|
| 158 |
+
_curses.KEY_UNDO: 'kund',
|
| 159 |
+
_curses.KEY_UP: 'kcuu1'
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
def has_key(ch):
|
| 163 |
+
if isinstance(ch, str):
|
| 164 |
+
ch = ord(ch)
|
| 165 |
+
|
| 166 |
+
# Figure out the correct capability name for the keycode.
|
| 167 |
+
capability_name = _capability_names.get(ch)
|
| 168 |
+
if capability_name is None:
|
| 169 |
+
return False
|
| 170 |
+
|
| 171 |
+
#Check the current terminal description for that capability;
|
| 172 |
+
#if present, return true, else return false.
|
| 173 |
+
if _curses.tigetstr( capability_name ):
|
| 174 |
+
return True
|
| 175 |
+
else:
|
| 176 |
+
return False
|
| 177 |
+
|
| 178 |
+
if __name__ == '__main__':
|
| 179 |
+
# Compare the output of this implementation and the ncurses has_key,
|
| 180 |
+
# on platforms where has_key is already available
|
| 181 |
+
try:
|
| 182 |
+
L = []
|
| 183 |
+
_curses.initscr()
|
| 184 |
+
for key in _capability_names.keys():
|
| 185 |
+
system = _curses.has_key(key)
|
| 186 |
+
python = has_key(key)
|
| 187 |
+
if system != python:
|
| 188 |
+
L.append( 'Mismatch for key %s, system=%i, Python=%i'
|
| 189 |
+
% (_curses.keyname( key ), system, python) )
|
| 190 |
+
finally:
|
| 191 |
+
_curses.endwin()
|
| 192 |
+
for i in L: print(i)
|
micromamba_root/envs/pytorch_env/Lib/curses/panel.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""curses.panel
|
| 2 |
+
|
| 3 |
+
Module for using panels with curses.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from _curses_panel import *
|
micromamba_root/envs/pytorch_env/Lib/curses/textpad.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Simple textbox editing widget with Emacs-like keybindings."""
|
| 2 |
+
|
| 3 |
+
import curses
|
| 4 |
+
import curses.ascii
|
| 5 |
+
|
| 6 |
+
def rectangle(win, uly, ulx, lry, lrx):
|
| 7 |
+
"""Draw a rectangle with corners at the provided upper-left
|
| 8 |
+
and lower-right coordinates.
|
| 9 |
+
"""
|
| 10 |
+
win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1)
|
| 11 |
+
win.hline(uly, ulx+1, curses.ACS_HLINE, lrx - ulx - 1)
|
| 12 |
+
win.hline(lry, ulx+1, curses.ACS_HLINE, lrx - ulx - 1)
|
| 13 |
+
win.vline(uly+1, lrx, curses.ACS_VLINE, lry - uly - 1)
|
| 14 |
+
win.addch(uly, ulx, curses.ACS_ULCORNER)
|
| 15 |
+
win.addch(uly, lrx, curses.ACS_URCORNER)
|
| 16 |
+
win.addch(lry, lrx, curses.ACS_LRCORNER)
|
| 17 |
+
win.addch(lry, ulx, curses.ACS_LLCORNER)
|
| 18 |
+
|
| 19 |
+
class Textbox:
|
| 20 |
+
"""Editing widget using the interior of a window object.
|
| 21 |
+
Supports the following Emacs-like key bindings:
|
| 22 |
+
|
| 23 |
+
Ctrl-A Go to left edge of window.
|
| 24 |
+
Ctrl-B Cursor left, wrapping to previous line if appropriate.
|
| 25 |
+
Ctrl-D Delete character under cursor.
|
| 26 |
+
Ctrl-E Go to right edge (stripspaces off) or end of line (stripspaces on).
|
| 27 |
+
Ctrl-F Cursor right, wrapping to next line when appropriate.
|
| 28 |
+
Ctrl-G Terminate, returning the window contents.
|
| 29 |
+
Ctrl-H Delete character backward.
|
| 30 |
+
Ctrl-J Terminate if the window is 1 line, otherwise insert newline.
|
| 31 |
+
Ctrl-K If line is blank, delete it, otherwise clear to end of line.
|
| 32 |
+
Ctrl-L Refresh screen.
|
| 33 |
+
Ctrl-N Cursor down; move down one line.
|
| 34 |
+
Ctrl-O Insert a blank line at cursor location.
|
| 35 |
+
Ctrl-P Cursor up; move up one line.
|
| 36 |
+
|
| 37 |
+
Move operations do nothing if the cursor is at an edge where the movement
|
| 38 |
+
is not possible. The following synonyms are supported where possible:
|
| 39 |
+
|
| 40 |
+
KEY_LEFT = Ctrl-B, KEY_RIGHT = Ctrl-F, KEY_UP = Ctrl-P, KEY_DOWN = Ctrl-N
|
| 41 |
+
KEY_BACKSPACE = Ctrl-h
|
| 42 |
+
"""
|
| 43 |
+
def __init__(self, win, insert_mode=False):
|
| 44 |
+
self.win = win
|
| 45 |
+
self.insert_mode = insert_mode
|
| 46 |
+
self._update_max_yx()
|
| 47 |
+
self.stripspaces = 1
|
| 48 |
+
self.lastcmd = None
|
| 49 |
+
win.keypad(1)
|
| 50 |
+
|
| 51 |
+
def _update_max_yx(self):
|
| 52 |
+
maxy, maxx = self.win.getmaxyx()
|
| 53 |
+
self.maxy = maxy - 1
|
| 54 |
+
self.maxx = maxx - 1
|
| 55 |
+
|
| 56 |
+
def _end_of_line(self, y):
|
| 57 |
+
"""Go to the location of the first blank on the given line,
|
| 58 |
+
returning the index of the last non-blank character."""
|
| 59 |
+
self._update_max_yx()
|
| 60 |
+
last = self.maxx
|
| 61 |
+
while True:
|
| 62 |
+
if curses.ascii.ascii(self.win.inch(y, last)) != curses.ascii.SP:
|
| 63 |
+
last = min(self.maxx, last+1)
|
| 64 |
+
break
|
| 65 |
+
elif last == 0:
|
| 66 |
+
break
|
| 67 |
+
last = last - 1
|
| 68 |
+
return last
|
| 69 |
+
|
| 70 |
+
def _insert_printable_char(self, ch):
|
| 71 |
+
self._update_max_yx()
|
| 72 |
+
(y, x) = self.win.getyx()
|
| 73 |
+
backyx = None
|
| 74 |
+
while y < self.maxy or x < self.maxx:
|
| 75 |
+
if self.insert_mode:
|
| 76 |
+
oldch = self.win.inch()
|
| 77 |
+
# The try-catch ignores the error we trigger from some curses
|
| 78 |
+
# versions by trying to write into the lowest-rightmost spot
|
| 79 |
+
# in the window.
|
| 80 |
+
try:
|
| 81 |
+
self.win.addch(ch)
|
| 82 |
+
except curses.error:
|
| 83 |
+
pass
|
| 84 |
+
if not self.insert_mode or not curses.ascii.isprint(oldch):
|
| 85 |
+
break
|
| 86 |
+
ch = oldch
|
| 87 |
+
(y, x) = self.win.getyx()
|
| 88 |
+
# Remember where to put the cursor back since we are in insert_mode
|
| 89 |
+
if backyx is None:
|
| 90 |
+
backyx = y, x
|
| 91 |
+
|
| 92 |
+
if backyx is not None:
|
| 93 |
+
self.win.move(*backyx)
|
| 94 |
+
|
| 95 |
+
def do_command(self, ch):
|
| 96 |
+
"Process a single editing command."
|
| 97 |
+
self._update_max_yx()
|
| 98 |
+
(y, x) = self.win.getyx()
|
| 99 |
+
self.lastcmd = ch
|
| 100 |
+
if curses.ascii.isprint(ch):
|
| 101 |
+
if y < self.maxy or x < self.maxx:
|
| 102 |
+
self._insert_printable_char(ch)
|
| 103 |
+
elif ch == curses.ascii.SOH: # ^a
|
| 104 |
+
self.win.move(y, 0)
|
| 105 |
+
elif ch in (curses.ascii.STX,curses.KEY_LEFT, curses.ascii.BS,curses.KEY_BACKSPACE):
|
| 106 |
+
if x > 0:
|
| 107 |
+
self.win.move(y, x-1)
|
| 108 |
+
elif y == 0:
|
| 109 |
+
pass
|
| 110 |
+
elif self.stripspaces:
|
| 111 |
+
self.win.move(y-1, self._end_of_line(y-1))
|
| 112 |
+
else:
|
| 113 |
+
self.win.move(y-1, self.maxx)
|
| 114 |
+
if ch in (curses.ascii.BS, curses.KEY_BACKSPACE):
|
| 115 |
+
self.win.delch()
|
| 116 |
+
elif ch == curses.ascii.EOT: # ^d
|
| 117 |
+
self.win.delch()
|
| 118 |
+
elif ch == curses.ascii.ENQ: # ^e
|
| 119 |
+
if self.stripspaces:
|
| 120 |
+
self.win.move(y, self._end_of_line(y))
|
| 121 |
+
else:
|
| 122 |
+
self.win.move(y, self.maxx)
|
| 123 |
+
elif ch in (curses.ascii.ACK, curses.KEY_RIGHT): # ^f
|
| 124 |
+
if x < self.maxx:
|
| 125 |
+
self.win.move(y, x+1)
|
| 126 |
+
elif y == self.maxy:
|
| 127 |
+
pass
|
| 128 |
+
else:
|
| 129 |
+
self.win.move(y+1, 0)
|
| 130 |
+
elif ch == curses.ascii.BEL: # ^g
|
| 131 |
+
return 0
|
| 132 |
+
elif ch == curses.ascii.NL: # ^j
|
| 133 |
+
if self.maxy == 0:
|
| 134 |
+
return 0
|
| 135 |
+
elif y < self.maxy:
|
| 136 |
+
self.win.move(y+1, 0)
|
| 137 |
+
elif ch == curses.ascii.VT: # ^k
|
| 138 |
+
if x == 0 and self._end_of_line(y) == 0:
|
| 139 |
+
self.win.deleteln()
|
| 140 |
+
else:
|
| 141 |
+
# first undo the effect of self._end_of_line
|
| 142 |
+
self.win.move(y, x)
|
| 143 |
+
self.win.clrtoeol()
|
| 144 |
+
elif ch == curses.ascii.FF: # ^l
|
| 145 |
+
self.win.refresh()
|
| 146 |
+
elif ch in (curses.ascii.SO, curses.KEY_DOWN): # ^n
|
| 147 |
+
if y < self.maxy:
|
| 148 |
+
self.win.move(y+1, x)
|
| 149 |
+
if x > self._end_of_line(y+1):
|
| 150 |
+
self.win.move(y+1, self._end_of_line(y+1))
|
| 151 |
+
elif ch == curses.ascii.SI: # ^o
|
| 152 |
+
self.win.insertln()
|
| 153 |
+
elif ch in (curses.ascii.DLE, curses.KEY_UP): # ^p
|
| 154 |
+
if y > 0:
|
| 155 |
+
self.win.move(y-1, x)
|
| 156 |
+
if x > self._end_of_line(y-1):
|
| 157 |
+
self.win.move(y-1, self._end_of_line(y-1))
|
| 158 |
+
return 1
|
| 159 |
+
|
| 160 |
+
def gather(self):
|
| 161 |
+
"Collect and return the contents of the window."
|
| 162 |
+
result = ""
|
| 163 |
+
self._update_max_yx()
|
| 164 |
+
for y in range(self.maxy+1):
|
| 165 |
+
self.win.move(y, 0)
|
| 166 |
+
stop = self._end_of_line(y)
|
| 167 |
+
if stop == 0 and self.stripspaces:
|
| 168 |
+
continue
|
| 169 |
+
for x in range(self.maxx+1):
|
| 170 |
+
if self.stripspaces and x > stop:
|
| 171 |
+
break
|
| 172 |
+
result = result + chr(curses.ascii.ascii(self.win.inch(y, x)))
|
| 173 |
+
if self.maxy > 0:
|
| 174 |
+
result = result + "\n"
|
| 175 |
+
return result
|
| 176 |
+
|
| 177 |
+
def edit(self, validate=None):
|
| 178 |
+
"Edit in the widget window and collect the results."
|
| 179 |
+
while 1:
|
| 180 |
+
ch = self.win.getch()
|
| 181 |
+
if validate:
|
| 182 |
+
ch = validate(ch)
|
| 183 |
+
if not ch:
|
| 184 |
+
continue
|
| 185 |
+
if not self.do_command(ch):
|
| 186 |
+
break
|
| 187 |
+
self.win.refresh()
|
| 188 |
+
return self.gather()
|
| 189 |
+
|
| 190 |
+
if __name__ == '__main__':
|
| 191 |
+
def test_editbox(stdscr):
|
| 192 |
+
ncols, nlines = 9, 4
|
| 193 |
+
uly, ulx = 15, 20
|
| 194 |
+
stdscr.addstr(uly-2, ulx, "Use Ctrl-G to end editing.")
|
| 195 |
+
win = curses.newwin(nlines, ncols, uly, ulx)
|
| 196 |
+
rectangle(stdscr, uly-1, ulx-1, uly + nlines, ulx + ncols)
|
| 197 |
+
stdscr.refresh()
|
| 198 |
+
return Textbox(win).edit()
|
| 199 |
+
|
| 200 |
+
str = curses.wrapper(test_editbox)
|
| 201 |
+
print('Contents of text box:', repr(str))
|
micromamba_root/envs/pytorch_env/Lib/dbm/__init__.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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gnu, dbm.ndbm or dbm.dumb object, dependent on the
|
| 9 |
+
type of database being opened (determined by the whichdb function) in the case
|
| 10 |
+
of an existing dbm. If the dbm does not exist and the create or new flag ('c'
|
| 11 |
+
or 'n') was specified, the dbm type will be determined by the availability of
|
| 12 |
+
the modules (tested in the above order).
|
| 13 |
+
|
| 14 |
+
It has the following interface (key and data are strings):
|
| 15 |
+
|
| 16 |
+
d[key] = data # store data at key (may override data at
|
| 17 |
+
# existing key)
|
| 18 |
+
data = d[key] # retrieve data at key (raise KeyError if no
|
| 19 |
+
# such key)
|
| 20 |
+
del d[key] # delete data stored at key (raises KeyError
|
| 21 |
+
# if no such key)
|
| 22 |
+
flag = key in d # true if the key exists
|
| 23 |
+
list = d.keys() # return a list of all existing keys (slow!)
|
| 24 |
+
|
| 25 |
+
Future versions may change the order in which implementations are
|
| 26 |
+
tested for existence, and add interfaces to other dbm-like
|
| 27 |
+
implementations.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
__all__ = ['open', 'whichdb', 'error']
|
| 31 |
+
|
| 32 |
+
import io
|
| 33 |
+
import os
|
| 34 |
+
import struct
|
| 35 |
+
import sys
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class error(Exception):
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
_names = ['dbm.gnu', 'dbm.ndbm', 'dbm.dumb']
|
| 42 |
+
_defaultmod = None
|
| 43 |
+
_modules = {}
|
| 44 |
+
|
| 45 |
+
error = (error, OSError)
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
from dbm import ndbm
|
| 49 |
+
except ImportError:
|
| 50 |
+
ndbm = None
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def open(file, flag='r', mode=0o666):
|
| 54 |
+
"""Open or create database at path given by *file*.
|
| 55 |
+
|
| 56 |
+
Optional argument *flag* can be 'r' (default) for read-only access, 'w'
|
| 57 |
+
for read-write access of an existing database, 'c' for read-write access
|
| 58 |
+
to a new or existing database, and 'n' for read-write access to a new
|
| 59 |
+
database.
|
| 60 |
+
|
| 61 |
+
Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
|
| 62 |
+
only if it doesn't exist; and 'n' always creates a new database.
|
| 63 |
+
"""
|
| 64 |
+
global _defaultmod
|
| 65 |
+
if _defaultmod is None:
|
| 66 |
+
for name in _names:
|
| 67 |
+
try:
|
| 68 |
+
mod = __import__(name, fromlist=['open'])
|
| 69 |
+
except ImportError:
|
| 70 |
+
continue
|
| 71 |
+
if not _defaultmod:
|
| 72 |
+
_defaultmod = mod
|
| 73 |
+
_modules[name] = mod
|
| 74 |
+
if not _defaultmod:
|
| 75 |
+
raise ImportError("no dbm clone found; tried %s" % _names)
|
| 76 |
+
|
| 77 |
+
# guess the type of an existing database, if not creating a new one
|
| 78 |
+
result = whichdb(file) if 'n' not in flag else None
|
| 79 |
+
if result is None:
|
| 80 |
+
# db doesn't exist or 'n' flag was specified to create a new db
|
| 81 |
+
if 'c' in flag or 'n' in flag:
|
| 82 |
+
# file doesn't exist and the new flag was used so use default type
|
| 83 |
+
mod = _defaultmod
|
| 84 |
+
else:
|
| 85 |
+
raise error[0]("db file doesn't exist; "
|
| 86 |
+
"use 'c' or 'n' flag to create a new db")
|
| 87 |
+
elif result == "":
|
| 88 |
+
# db type cannot be determined
|
| 89 |
+
raise error[0]("db type could not be determined")
|
| 90 |
+
elif result not in _modules:
|
| 91 |
+
raise error[0]("db type is {0}, but the module is not "
|
| 92 |
+
"available".format(result))
|
| 93 |
+
else:
|
| 94 |
+
mod = _modules[result]
|
| 95 |
+
return mod.open(file, flag, mode)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def whichdb(filename):
|
| 99 |
+
"""Guess which db package to use to open a db file.
|
| 100 |
+
|
| 101 |
+
Return values:
|
| 102 |
+
|
| 103 |
+
- None if the database file can't be read;
|
| 104 |
+
- empty string if the file can be read but can't be recognized
|
| 105 |
+
- the name of the dbm submodule (e.g. "ndbm" or "gnu") if recognized.
|
| 106 |
+
|
| 107 |
+
Importing the given module may still fail, and opening the
|
| 108 |
+
database using that module may still fail.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
# Check for ndbm first -- this has a .pag and a .dir file
|
| 112 |
+
filename = os.fsencode(filename)
|
| 113 |
+
try:
|
| 114 |
+
f = io.open(filename + b".pag", "rb")
|
| 115 |
+
f.close()
|
| 116 |
+
f = io.open(filename + b".dir", "rb")
|
| 117 |
+
f.close()
|
| 118 |
+
return "dbm.ndbm"
|
| 119 |
+
except OSError:
|
| 120 |
+
# some dbm emulations based on Berkeley DB generate a .db file
|
| 121 |
+
# some do not, but they should be caught by the bsd checks
|
| 122 |
+
try:
|
| 123 |
+
f = io.open(filename + b".db", "rb")
|
| 124 |
+
f.close()
|
| 125 |
+
# guarantee we can actually open the file using dbm
|
| 126 |
+
# kind of overkill, but since we are dealing with emulations
|
| 127 |
+
# it seems like a prudent step
|
| 128 |
+
if ndbm is not None:
|
| 129 |
+
d = ndbm.open(filename)
|
| 130 |
+
d.close()
|
| 131 |
+
return "dbm.ndbm"
|
| 132 |
+
except OSError:
|
| 133 |
+
pass
|
| 134 |
+
|
| 135 |
+
# Check for dumbdbm next -- this has a .dir and a .dat file
|
| 136 |
+
try:
|
| 137 |
+
# First check for presence of files
|
| 138 |
+
os.stat(filename + b".dat")
|
| 139 |
+
size = os.stat(filename + b".dir").st_size
|
| 140 |
+
# dumbdbm files with no keys are empty
|
| 141 |
+
if size == 0:
|
| 142 |
+
return "dbm.dumb"
|
| 143 |
+
f = io.open(filename + b".dir", "rb")
|
| 144 |
+
try:
|
| 145 |
+
if f.read(1) in (b"'", b'"'):
|
| 146 |
+
return "dbm.dumb"
|
| 147 |
+
finally:
|
| 148 |
+
f.close()
|
| 149 |
+
except OSError:
|
| 150 |
+
pass
|
| 151 |
+
|
| 152 |
+
# See if the file exists, return None if not
|
| 153 |
+
try:
|
| 154 |
+
f = io.open(filename, "rb")
|
| 155 |
+
except OSError:
|
| 156 |
+
return None
|
| 157 |
+
|
| 158 |
+
with f:
|
| 159 |
+
# Read the start of the file -- the magic number
|
| 160 |
+
s16 = f.read(16)
|
| 161 |
+
s = s16[0:4]
|
| 162 |
+
|
| 163 |
+
# Return "" if not at least 4 bytes
|
| 164 |
+
if len(s) != 4:
|
| 165 |
+
return ""
|
| 166 |
+
|
| 167 |
+
# Convert to 4-byte int in native byte order -- return "" if impossible
|
| 168 |
+
try:
|
| 169 |
+
(magic,) = struct.unpack("=l", s)
|
| 170 |
+
except struct.error:
|
| 171 |
+
return ""
|
| 172 |
+
|
| 173 |
+
# Check for GNU dbm
|
| 174 |
+
if magic in (0x13579ace, 0x13579acd, 0x13579acf):
|
| 175 |
+
return "dbm.gnu"
|
| 176 |
+
|
| 177 |
+
# Later versions of Berkeley db hash file have a 12-byte pad in
|
| 178 |
+
# front of the file type
|
| 179 |
+
try:
|
| 180 |
+
(magic,) = struct.unpack("=l", s16[-4:])
|
| 181 |
+
except struct.error:
|
| 182 |
+
return ""
|
| 183 |
+
|
| 184 |
+
# Unknown
|
| 185 |
+
return ""
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
if __name__ == "__main__":
|
| 189 |
+
for filename in sys.argv[1:]:
|
| 190 |
+
print(whichdb(filename) or "UNKNOWN", filename)
|
micromamba_root/envs/pytorch_env/Lib/dbm/dumb.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A dumb and slow but simple dbm clone.
|
| 2 |
+
|
| 3 |
+
For database spam, spam.dir contains the index (a text file),
|
| 4 |
+
spam.bak *may* contain a backup of the index (also a text file),
|
| 5 |
+
while spam.dat contains the data (a binary file).
|
| 6 |
+
|
| 7 |
+
XXX TO DO:
|
| 8 |
+
|
| 9 |
+
- seems to contain a bug when updating...
|
| 10 |
+
|
| 11 |
+
- reclaim free space (currently, space once occupied by deleted or expanded
|
| 12 |
+
items is never reused)
|
| 13 |
+
|
| 14 |
+
- support concurrent access (currently, if two processes take turns making
|
| 15 |
+
updates, they can mess up the index)
|
| 16 |
+
|
| 17 |
+
- support efficient access to large databases (currently, the whole index
|
| 18 |
+
is read when the database is opened, and some updates rewrite the whole index)
|
| 19 |
+
|
| 20 |
+
- support opening for read-only (flag = 'm')
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
import ast as _ast
|
| 25 |
+
import io as _io
|
| 26 |
+
import os as _os
|
| 27 |
+
import collections.abc
|
| 28 |
+
|
| 29 |
+
__all__ = ["error", "open"]
|
| 30 |
+
|
| 31 |
+
_BLOCKSIZE = 512
|
| 32 |
+
|
| 33 |
+
error = OSError
|
| 34 |
+
|
| 35 |
+
class _Database(collections.abc.MutableMapping):
|
| 36 |
+
|
| 37 |
+
# The on-disk directory and data files can remain in mutually
|
| 38 |
+
# inconsistent states for an arbitrarily long time (see comments
|
| 39 |
+
# at the end of __setitem__). This is only repaired when _commit()
|
| 40 |
+
# gets called. One place _commit() gets called is from __del__(),
|
| 41 |
+
# and if that occurs at program shutdown time, module globals may
|
| 42 |
+
# already have gotten rebound to None. Since it's crucial that
|
| 43 |
+
# _commit() finish successfully, we can't ignore shutdown races
|
| 44 |
+
# here, and _commit() must not reference any globals.
|
| 45 |
+
_os = _os # for _commit()
|
| 46 |
+
_io = _io # for _commit()
|
| 47 |
+
|
| 48 |
+
def __init__(self, filebasename, mode, flag='c'):
|
| 49 |
+
filebasename = self._os.fsencode(filebasename)
|
| 50 |
+
self._mode = mode
|
| 51 |
+
self._readonly = (flag == 'r')
|
| 52 |
+
|
| 53 |
+
# The directory file is a text file. Each line looks like
|
| 54 |
+
# "%r, (%d, %d)\n" % (key, pos, siz)
|
| 55 |
+
# where key is the string key, pos is the offset into the dat
|
| 56 |
+
# file of the associated value's first byte, and siz is the number
|
| 57 |
+
# of bytes in the associated value.
|
| 58 |
+
self._dirfile = filebasename + b'.dir'
|
| 59 |
+
|
| 60 |
+
# The data file is a binary file pointed into by the directory
|
| 61 |
+
# file, and holds the values associated with keys. Each value
|
| 62 |
+
# begins at a _BLOCKSIZE-aligned byte offset, and is a raw
|
| 63 |
+
# binary 8-bit string value.
|
| 64 |
+
self._datfile = filebasename + b'.dat'
|
| 65 |
+
self._bakfile = filebasename + b'.bak'
|
| 66 |
+
|
| 67 |
+
# The index is an in-memory dict, mirroring the directory file.
|
| 68 |
+
self._index = None # maps keys to (pos, siz) pairs
|
| 69 |
+
|
| 70 |
+
# Handle the creation
|
| 71 |
+
self._create(flag)
|
| 72 |
+
self._update(flag)
|
| 73 |
+
|
| 74 |
+
def _create(self, flag):
|
| 75 |
+
if flag == 'n':
|
| 76 |
+
for filename in (self._datfile, self._bakfile, self._dirfile):
|
| 77 |
+
try:
|
| 78 |
+
_os.remove(filename)
|
| 79 |
+
except OSError:
|
| 80 |
+
pass
|
| 81 |
+
# Mod by Jack: create data file if needed
|
| 82 |
+
try:
|
| 83 |
+
f = _io.open(self._datfile, 'r', encoding="Latin-1")
|
| 84 |
+
except OSError:
|
| 85 |
+
if flag not in ('c', 'n'):
|
| 86 |
+
raise
|
| 87 |
+
with _io.open(self._datfile, 'w', encoding="Latin-1") as f:
|
| 88 |
+
self._chmod(self._datfile)
|
| 89 |
+
else:
|
| 90 |
+
f.close()
|
| 91 |
+
|
| 92 |
+
# Read directory file into the in-memory index dict.
|
| 93 |
+
def _update(self, flag):
|
| 94 |
+
self._modified = False
|
| 95 |
+
self._index = {}
|
| 96 |
+
try:
|
| 97 |
+
f = _io.open(self._dirfile, 'r', encoding="Latin-1")
|
| 98 |
+
except OSError:
|
| 99 |
+
if flag not in ('c', 'n'):
|
| 100 |
+
raise
|
| 101 |
+
self._modified = True
|
| 102 |
+
else:
|
| 103 |
+
with f:
|
| 104 |
+
for line in f:
|
| 105 |
+
line = line.rstrip()
|
| 106 |
+
key, pos_and_siz_pair = _ast.literal_eval(line)
|
| 107 |
+
key = key.encode('Latin-1')
|
| 108 |
+
self._index[key] = pos_and_siz_pair
|
| 109 |
+
|
| 110 |
+
# Write the index dict to the directory file. The original directory
|
| 111 |
+
# file (if any) is renamed with a .bak extension first. If a .bak
|
| 112 |
+
# file currently exists, it's deleted.
|
| 113 |
+
def _commit(self):
|
| 114 |
+
# CAUTION: It's vital that _commit() succeed, and _commit() can
|
| 115 |
+
# be called from __del__(). Therefore we must never reference a
|
| 116 |
+
# global in this routine.
|
| 117 |
+
if self._index is None or not self._modified:
|
| 118 |
+
return # nothing to do
|
| 119 |
+
|
| 120 |
+
try:
|
| 121 |
+
self._os.unlink(self._bakfile)
|
| 122 |
+
except OSError:
|
| 123 |
+
pass
|
| 124 |
+
|
| 125 |
+
try:
|
| 126 |
+
self._os.rename(self._dirfile, self._bakfile)
|
| 127 |
+
except OSError:
|
| 128 |
+
pass
|
| 129 |
+
|
| 130 |
+
with self._io.open(self._dirfile, 'w', encoding="Latin-1") as f:
|
| 131 |
+
self._chmod(self._dirfile)
|
| 132 |
+
for key, pos_and_siz_pair in self._index.items():
|
| 133 |
+
# Use Latin-1 since it has no qualms with any value in any
|
| 134 |
+
# position; UTF-8, though, does care sometimes.
|
| 135 |
+
entry = "%r, %r\n" % (key.decode('Latin-1'), pos_and_siz_pair)
|
| 136 |
+
f.write(entry)
|
| 137 |
+
|
| 138 |
+
sync = _commit
|
| 139 |
+
|
| 140 |
+
def _verify_open(self):
|
| 141 |
+
if self._index is None:
|
| 142 |
+
raise error('DBM object has already been closed')
|
| 143 |
+
|
| 144 |
+
def __getitem__(self, key):
|
| 145 |
+
if isinstance(key, str):
|
| 146 |
+
key = key.encode('utf-8')
|
| 147 |
+
self._verify_open()
|
| 148 |
+
pos, siz = self._index[key] # may raise KeyError
|
| 149 |
+
with _io.open(self._datfile, 'rb') as f:
|
| 150 |
+
f.seek(pos)
|
| 151 |
+
dat = f.read(siz)
|
| 152 |
+
return dat
|
| 153 |
+
|
| 154 |
+
# Append val to the data file, starting at a _BLOCKSIZE-aligned
|
| 155 |
+
# offset. The data file is first padded with NUL bytes (if needed)
|
| 156 |
+
# to get to an aligned offset. Return pair
|
| 157 |
+
# (starting offset of val, len(val))
|
| 158 |
+
def _addval(self, val):
|
| 159 |
+
with _io.open(self._datfile, 'rb+') as f:
|
| 160 |
+
f.seek(0, 2)
|
| 161 |
+
pos = int(f.tell())
|
| 162 |
+
npos = ((pos + _BLOCKSIZE - 1) // _BLOCKSIZE) * _BLOCKSIZE
|
| 163 |
+
f.write(b'\0'*(npos-pos))
|
| 164 |
+
pos = npos
|
| 165 |
+
f.write(val)
|
| 166 |
+
return (pos, len(val))
|
| 167 |
+
|
| 168 |
+
# Write val to the data file, starting at offset pos. The caller
|
| 169 |
+
# is responsible for ensuring that there's enough room starting at
|
| 170 |
+
# pos to hold val, without overwriting some other value. Return
|
| 171 |
+
# pair (pos, len(val)).
|
| 172 |
+
def _setval(self, pos, val):
|
| 173 |
+
with _io.open(self._datfile, 'rb+') as f:
|
| 174 |
+
f.seek(pos)
|
| 175 |
+
f.write(val)
|
| 176 |
+
return (pos, len(val))
|
| 177 |
+
|
| 178 |
+
# key is a new key whose associated value starts in the data file
|
| 179 |
+
# at offset pos and with length siz. Add an index record to
|
| 180 |
+
# the in-memory index dict, and append one to the directory file.
|
| 181 |
+
def _addkey(self, key, pos_and_siz_pair):
|
| 182 |
+
self._index[key] = pos_and_siz_pair
|
| 183 |
+
with _io.open(self._dirfile, 'a', encoding="Latin-1") as f:
|
| 184 |
+
self._chmod(self._dirfile)
|
| 185 |
+
f.write("%r, %r\n" % (key.decode("Latin-1"), pos_and_siz_pair))
|
| 186 |
+
|
| 187 |
+
def __setitem__(self, key, val):
|
| 188 |
+
if self._readonly:
|
| 189 |
+
raise error('The database is opened for reading only')
|
| 190 |
+
if isinstance(key, str):
|
| 191 |
+
key = key.encode('utf-8')
|
| 192 |
+
elif not isinstance(key, (bytes, bytearray)):
|
| 193 |
+
raise TypeError("keys must be bytes or strings")
|
| 194 |
+
if isinstance(val, str):
|
| 195 |
+
val = val.encode('utf-8')
|
| 196 |
+
elif not isinstance(val, (bytes, bytearray)):
|
| 197 |
+
raise TypeError("values must be bytes or strings")
|
| 198 |
+
self._verify_open()
|
| 199 |
+
self._modified = True
|
| 200 |
+
if key not in self._index:
|
| 201 |
+
self._addkey(key, self._addval(val))
|
| 202 |
+
else:
|
| 203 |
+
# See whether the new value is small enough to fit in the
|
| 204 |
+
# (padded) space currently occupied by the old value.
|
| 205 |
+
pos, siz = self._index[key]
|
| 206 |
+
oldblocks = (siz + _BLOCKSIZE - 1) // _BLOCKSIZE
|
| 207 |
+
newblocks = (len(val) + _BLOCKSIZE - 1) // _BLOCKSIZE
|
| 208 |
+
if newblocks <= oldblocks:
|
| 209 |
+
self._index[key] = self._setval(pos, val)
|
| 210 |
+
else:
|
| 211 |
+
# The new value doesn't fit in the (padded) space used
|
| 212 |
+
# by the old value. The blocks used by the old value are
|
| 213 |
+
# forever lost.
|
| 214 |
+
self._index[key] = self._addval(val)
|
| 215 |
+
|
| 216 |
+
# Note that _index may be out of synch with the directory
|
| 217 |
+
# file now: _setval() and _addval() don't update the directory
|
| 218 |
+
# file. This also means that the on-disk directory and data
|
| 219 |
+
# files are in a mutually inconsistent state, and they'll
|
| 220 |
+
# remain that way until _commit() is called. Note that this
|
| 221 |
+
# is a disaster (for the database) if the program crashes
|
| 222 |
+
# (so that _commit() never gets called).
|
| 223 |
+
|
| 224 |
+
def __delitem__(self, key):
|
| 225 |
+
if self._readonly:
|
| 226 |
+
raise error('The database is opened for reading only')
|
| 227 |
+
if isinstance(key, str):
|
| 228 |
+
key = key.encode('utf-8')
|
| 229 |
+
self._verify_open()
|
| 230 |
+
self._modified = True
|
| 231 |
+
# The blocks used by the associated value are lost.
|
| 232 |
+
del self._index[key]
|
| 233 |
+
# XXX It's unclear why we do a _commit() here (the code always
|
| 234 |
+
# XXX has, so I'm not changing it). __setitem__ doesn't try to
|
| 235 |
+
# XXX keep the directory file in synch. Why should we? Or
|
| 236 |
+
# XXX why shouldn't __setitem__?
|
| 237 |
+
self._commit()
|
| 238 |
+
|
| 239 |
+
def keys(self):
|
| 240 |
+
try:
|
| 241 |
+
return list(self._index)
|
| 242 |
+
except TypeError:
|
| 243 |
+
raise error('DBM object has already been closed') from None
|
| 244 |
+
|
| 245 |
+
def items(self):
|
| 246 |
+
self._verify_open()
|
| 247 |
+
return [(key, self[key]) for key in self._index.keys()]
|
| 248 |
+
|
| 249 |
+
def __contains__(self, key):
|
| 250 |
+
if isinstance(key, str):
|
| 251 |
+
key = key.encode('utf-8')
|
| 252 |
+
try:
|
| 253 |
+
return key in self._index
|
| 254 |
+
except TypeError:
|
| 255 |
+
if self._index is None:
|
| 256 |
+
raise error('DBM object has already been closed') from None
|
| 257 |
+
else:
|
| 258 |
+
raise
|
| 259 |
+
|
| 260 |
+
def iterkeys(self):
|
| 261 |
+
try:
|
| 262 |
+
return iter(self._index)
|
| 263 |
+
except TypeError:
|
| 264 |
+
raise error('DBM object has already been closed') from None
|
| 265 |
+
__iter__ = iterkeys
|
| 266 |
+
|
| 267 |
+
def __len__(self):
|
| 268 |
+
try:
|
| 269 |
+
return len(self._index)
|
| 270 |
+
except TypeError:
|
| 271 |
+
raise error('DBM object has already been closed') from None
|
| 272 |
+
|
| 273 |
+
def close(self):
|
| 274 |
+
try:
|
| 275 |
+
self._commit()
|
| 276 |
+
finally:
|
| 277 |
+
self._index = self._datfile = self._dirfile = self._bakfile = None
|
| 278 |
+
|
| 279 |
+
__del__ = close
|
| 280 |
+
|
| 281 |
+
def _chmod(self, file):
|
| 282 |
+
self._os.chmod(file, self._mode)
|
| 283 |
+
|
| 284 |
+
def __enter__(self):
|
| 285 |
+
return self
|
| 286 |
+
|
| 287 |
+
def __exit__(self, *args):
|
| 288 |
+
self.close()
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def open(file, flag='c', mode=0o666):
|
| 292 |
+
"""Open the database file, filename, and return corresponding object.
|
| 293 |
+
|
| 294 |
+
The flag argument, used to control how the database is opened in the
|
| 295 |
+
other DBM implementations, supports only the semantics of 'c' and 'n'
|
| 296 |
+
values. Other values will default to the semantics of 'c' value:
|
| 297 |
+
the database will always opened for update and will be created if it
|
| 298 |
+
does not exist.
|
| 299 |
+
|
| 300 |
+
The optional mode argument is the UNIX mode of the file, used only when
|
| 301 |
+
the database has to be created. It defaults to octal code 0o666 (and
|
| 302 |
+
will be modified by the prevailing umask).
|
| 303 |
+
|
| 304 |
+
"""
|
| 305 |
+
|
| 306 |
+
# Modify mode depending on the umask
|
| 307 |
+
try:
|
| 308 |
+
um = _os.umask(0)
|
| 309 |
+
_os.umask(um)
|
| 310 |
+
except AttributeError:
|
| 311 |
+
pass
|
| 312 |
+
else:
|
| 313 |
+
# Turn off any bits that are set in the umask
|
| 314 |
+
mode = mode & (~um)
|
| 315 |
+
if flag not in ('r', 'w', 'c', 'n'):
|
| 316 |
+
raise ValueError("Flag must be one of 'r', 'w', 'c', or 'n'")
|
| 317 |
+
return _Database(file, mode, flag=flag)
|
micromamba_root/envs/pytorch_env/Lib/dbm/gnu.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provide the _gdbm module as a dbm submodule."""
|
| 2 |
+
|
| 3 |
+
from _gdbm import *
|
micromamba_root/envs/pytorch_env/Lib/dbm/ndbm.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Provide the _dbm module as a dbm submodule."""
|
| 2 |
+
|
| 3 |
+
from _dbm import *
|