events.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. """Event loop and event loop policy."""
  2. __all__ = (
  3. 'AbstractEventLoopPolicy',
  4. 'AbstractEventLoop', 'AbstractServer',
  5. 'Handle', 'TimerHandle',
  6. 'get_event_loop_policy', 'set_event_loop_policy',
  7. 'get_event_loop', 'set_event_loop', 'new_event_loop',
  8. 'get_child_watcher', 'set_child_watcher',
  9. '_set_running_loop', 'get_running_loop',
  10. '_get_running_loop',
  11. )
  12. import contextvars
  13. import os
  14. import socket
  15. import subprocess
  16. import sys
  17. import threading
  18. from . import format_helpers
  19. class Handle:
  20. """Object returned by callback registration methods."""
  21. __slots__ = ('_callback', '_args', '_cancelled', '_loop',
  22. '_source_traceback', '_repr', '__weakref__',
  23. '_context')
  24. def __init__(self, callback, args, loop, context=None):
  25. if context is None:
  26. context = contextvars.copy_context()
  27. self._context = context
  28. self._loop = loop
  29. self._callback = callback
  30. self._args = args
  31. self._cancelled = False
  32. self._repr = None
  33. if self._loop.get_debug():
  34. self._source_traceback = format_helpers.extract_stack(
  35. sys._getframe(1))
  36. else:
  37. self._source_traceback = None
  38. def _repr_info(self):
  39. info = [self.__class__.__name__]
  40. if self._cancelled:
  41. info.append('cancelled')
  42. if self._callback is not None:
  43. info.append(format_helpers._format_callback_source(
  44. self._callback, self._args))
  45. if self._source_traceback:
  46. frame = self._source_traceback[-1]
  47. info.append(f'created at {frame[0]}:{frame[1]}')
  48. return info
  49. def __repr__(self):
  50. if self._repr is not None:
  51. return self._repr
  52. info = self._repr_info()
  53. return '<{}>'.format(' '.join(info))
  54. def cancel(self):
  55. if not self._cancelled:
  56. self._cancelled = True
  57. if self._loop.get_debug():
  58. # Keep a representation in debug mode to keep callback and
  59. # parameters. For example, to log the warning
  60. # "Executing <Handle...> took 2.5 second"
  61. self._repr = repr(self)
  62. self._callback = None
  63. self._args = None
  64. def cancelled(self):
  65. return self._cancelled
  66. def _run(self):
  67. try:
  68. self._context.run(self._callback, *self._args)
  69. except (SystemExit, KeyboardInterrupt):
  70. raise
  71. except BaseException as exc:
  72. cb = format_helpers._format_callback_source(
  73. self._callback, self._args)
  74. msg = f'Exception in callback {cb}'
  75. context = {
  76. 'message': msg,
  77. 'exception': exc,
  78. 'handle': self,
  79. }
  80. if self._source_traceback:
  81. context['source_traceback'] = self._source_traceback
  82. self._loop.call_exception_handler(context)
  83. self = None # Needed to break cycles when an exception occurs.
  84. class TimerHandle(Handle):
  85. """Object returned by timed callback registration methods."""
  86. __slots__ = ['_scheduled', '_when']
  87. def __init__(self, when, callback, args, loop, context=None):
  88. assert when is not None
  89. super().__init__(callback, args, loop, context)
  90. if self._source_traceback:
  91. del self._source_traceback[-1]
  92. self._when = when
  93. self._scheduled = False
  94. def _repr_info(self):
  95. info = super()._repr_info()
  96. pos = 2 if self._cancelled else 1
  97. info.insert(pos, f'when={self._when}')
  98. return info
  99. def __hash__(self):
  100. return hash(self._when)
  101. def __lt__(self, other):
  102. if isinstance(other, TimerHandle):
  103. return self._when < other._when
  104. return NotImplemented
  105. def __le__(self, other):
  106. if isinstance(other, TimerHandle):
  107. return self._when < other._when or self.__eq__(other)
  108. return NotImplemented
  109. def __gt__(self, other):
  110. if isinstance(other, TimerHandle):
  111. return self._when > other._when
  112. return NotImplemented
  113. def __ge__(self, other):
  114. if isinstance(other, TimerHandle):
  115. return self._when > other._when or self.__eq__(other)
  116. return NotImplemented
  117. def __eq__(self, other):
  118. if isinstance(other, TimerHandle):
  119. return (self._when == other._when and
  120. self._callback == other._callback and
  121. self._args == other._args and
  122. self._cancelled == other._cancelled)
  123. return NotImplemented
  124. def cancel(self):
  125. if not self._cancelled:
  126. self._loop._timer_handle_cancelled(self)
  127. super().cancel()
  128. def when(self):
  129. """Return a scheduled callback time.
  130. The time is an absolute timestamp, using the same time
  131. reference as loop.time().
  132. """
  133. return self._when
  134. class AbstractServer:
  135. """Abstract server returned by create_server()."""
  136. def close(self):
  137. """Stop serving. This leaves existing connections open."""
  138. raise NotImplementedError
  139. def get_loop(self):
  140. """Get the event loop the Server object is attached to."""
  141. raise NotImplementedError
  142. def is_serving(self):
  143. """Return True if the server is accepting connections."""
  144. raise NotImplementedError
  145. async def start_serving(self):
  146. """Start accepting connections.
  147. This method is idempotent, so it can be called when
  148. the server is already being serving.
  149. """
  150. raise NotImplementedError
  151. async def serve_forever(self):
  152. """Start accepting connections until the coroutine is cancelled.
  153. The server is closed when the coroutine is cancelled.
  154. """
  155. raise NotImplementedError
  156. async def wait_closed(self):
  157. """Coroutine to wait until service is closed."""
  158. raise NotImplementedError
  159. async def __aenter__(self):
  160. return self
  161. async def __aexit__(self, *exc):
  162. self.close()
  163. await self.wait_closed()
  164. class AbstractEventLoop:
  165. """Abstract event loop."""
  166. # Running and stopping the event loop.
  167. def run_forever(self):
  168. """Run the event loop until stop() is called."""
  169. raise NotImplementedError
  170. def run_until_complete(self, future):
  171. """Run the event loop until a Future is done.
  172. Return the Future's result, or raise its exception.
  173. """
  174. raise NotImplementedError
  175. def stop(self):
  176. """Stop the event loop as soon as reasonable.
  177. Exactly how soon that is may depend on the implementation, but
  178. no more I/O callbacks should be scheduled.
  179. """
  180. raise NotImplementedError
  181. def is_running(self):
  182. """Return whether the event loop is currently running."""
  183. raise NotImplementedError
  184. def is_closed(self):
  185. """Returns True if the event loop was closed."""
  186. raise NotImplementedError
  187. def close(self):
  188. """Close the loop.
  189. The loop should not be running.
  190. This is idempotent and irreversible.
  191. No other methods should be called after this one.
  192. """
  193. raise NotImplementedError
  194. async def shutdown_asyncgens(self):
  195. """Shutdown all active asynchronous generators."""
  196. raise NotImplementedError
  197. async def shutdown_default_executor(self):
  198. """Schedule the shutdown of the default executor."""
  199. raise NotImplementedError
  200. # Methods scheduling callbacks. All these return Handles.
  201. def _timer_handle_cancelled(self, handle):
  202. """Notification that a TimerHandle has been cancelled."""
  203. raise NotImplementedError
  204. def call_soon(self, callback, *args, context=None):
  205. return self.call_later(0, callback, *args, context=context)
  206. def call_later(self, delay, callback, *args, context=None):
  207. raise NotImplementedError
  208. def call_at(self, when, callback, *args, context=None):
  209. raise NotImplementedError
  210. def time(self):
  211. raise NotImplementedError
  212. def create_future(self):
  213. raise NotImplementedError
  214. # Method scheduling a coroutine object: create a task.
  215. def create_task(self, coro, *, name=None):
  216. raise NotImplementedError
  217. # Methods for interacting with threads.
  218. def call_soon_threadsafe(self, callback, *args, context=None):
  219. raise NotImplementedError
  220. def run_in_executor(self, executor, func, *args):
  221. raise NotImplementedError
  222. def set_default_executor(self, executor):
  223. raise NotImplementedError
  224. # Network I/O methods returning Futures.
  225. async def getaddrinfo(self, host, port, *,
  226. family=0, type=0, proto=0, flags=0):
  227. raise NotImplementedError
  228. async def getnameinfo(self, sockaddr, flags=0):
  229. raise NotImplementedError
  230. async def create_connection(
  231. self, protocol_factory, host=None, port=None,
  232. *, ssl=None, family=0, proto=0,
  233. flags=0, sock=None, local_addr=None,
  234. server_hostname=None,
  235. ssl_handshake_timeout=None,
  236. happy_eyeballs_delay=None, interleave=None):
  237. raise NotImplementedError
  238. async def create_server(
  239. self, protocol_factory, host=None, port=None,
  240. *, family=socket.AF_UNSPEC,
  241. flags=socket.AI_PASSIVE, sock=None, backlog=100,
  242. ssl=None, reuse_address=None, reuse_port=None,
  243. ssl_handshake_timeout=None,
  244. start_serving=True):
  245. """A coroutine which creates a TCP server bound to host and port.
  246. The return value is a Server object which can be used to stop
  247. the service.
  248. If host is an empty string or None all interfaces are assumed
  249. and a list of multiple sockets will be returned (most likely
  250. one for IPv4 and another one for IPv6). The host parameter can also be
  251. a sequence (e.g. list) of hosts to bind to.
  252. family can be set to either AF_INET or AF_INET6 to force the
  253. socket to use IPv4 or IPv6. If not set it will be determined
  254. from host (defaults to AF_UNSPEC).
  255. flags is a bitmask for getaddrinfo().
  256. sock can optionally be specified in order to use a preexisting
  257. socket object.
  258. backlog is the maximum number of queued connections passed to
  259. listen() (defaults to 100).
  260. ssl can be set to an SSLContext to enable SSL over the
  261. accepted connections.
  262. reuse_address tells the kernel to reuse a local socket in
  263. TIME_WAIT state, without waiting for its natural timeout to
  264. expire. If not specified will automatically be set to True on
  265. UNIX.
  266. reuse_port tells the kernel to allow this endpoint to be bound to
  267. the same port as other existing endpoints are bound to, so long as
  268. they all set this flag when being created. This option is not
  269. supported on Windows.
  270. ssl_handshake_timeout is the time in seconds that an SSL server
  271. will wait for completion of the SSL handshake before aborting the
  272. connection. Default is 60s.
  273. start_serving set to True (default) causes the created server
  274. to start accepting connections immediately. When set to False,
  275. the user should await Server.start_serving() or Server.serve_forever()
  276. to make the server to start accepting connections.
  277. """
  278. raise NotImplementedError
  279. async def sendfile(self, transport, file, offset=0, count=None,
  280. *, fallback=True):
  281. """Send a file through a transport.
  282. Return an amount of sent bytes.
  283. """
  284. raise NotImplementedError
  285. async def start_tls(self, transport, protocol, sslcontext, *,
  286. server_side=False,
  287. server_hostname=None,
  288. ssl_handshake_timeout=None):
  289. """Upgrade a transport to TLS.
  290. Return a new transport that *protocol* should start using
  291. immediately.
  292. """
  293. raise NotImplementedError
  294. async def create_unix_connection(
  295. self, protocol_factory, path=None, *,
  296. ssl=None, sock=None,
  297. server_hostname=None,
  298. ssl_handshake_timeout=None):
  299. raise NotImplementedError
  300. async def create_unix_server(
  301. self, protocol_factory, path=None, *,
  302. sock=None, backlog=100, ssl=None,
  303. ssl_handshake_timeout=None,
  304. start_serving=True):
  305. """A coroutine which creates a UNIX Domain Socket server.
  306. The return value is a Server object, which can be used to stop
  307. the service.
  308. path is a str, representing a file system path to bind the
  309. server socket to.
  310. sock can optionally be specified in order to use a preexisting
  311. socket object.
  312. backlog is the maximum number of queued connections passed to
  313. listen() (defaults to 100).
  314. ssl can be set to an SSLContext to enable SSL over the
  315. accepted connections.
  316. ssl_handshake_timeout is the time in seconds that an SSL server
  317. will wait for the SSL handshake to complete (defaults to 60s).
  318. start_serving set to True (default) causes the created server
  319. to start accepting connections immediately. When set to False,
  320. the user should await Server.start_serving() or Server.serve_forever()
  321. to make the server to start accepting connections.
  322. """
  323. raise NotImplementedError
  324. async def create_datagram_endpoint(self, protocol_factory,
  325. local_addr=None, remote_addr=None, *,
  326. family=0, proto=0, flags=0,
  327. reuse_address=None, reuse_port=None,
  328. allow_broadcast=None, sock=None):
  329. """A coroutine which creates a datagram endpoint.
  330. This method will try to establish the endpoint in the background.
  331. When successful, the coroutine returns a (transport, protocol) pair.
  332. protocol_factory must be a callable returning a protocol instance.
  333. socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
  334. host (or family if specified), socket type SOCK_DGRAM.
  335. reuse_address tells the kernel to reuse a local socket in
  336. TIME_WAIT state, without waiting for its natural timeout to
  337. expire. If not specified it will automatically be set to True on
  338. UNIX.
  339. reuse_port tells the kernel to allow this endpoint to be bound to
  340. the same port as other existing endpoints are bound to, so long as
  341. they all set this flag when being created. This option is not
  342. supported on Windows and some UNIX's. If the
  343. :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
  344. capability is unsupported.
  345. allow_broadcast tells the kernel to allow this endpoint to send
  346. messages to the broadcast address.
  347. sock can optionally be specified in order to use a preexisting
  348. socket object.
  349. """
  350. raise NotImplementedError
  351. # Pipes and subprocesses.
  352. async def connect_read_pipe(self, protocol_factory, pipe):
  353. """Register read pipe in event loop. Set the pipe to non-blocking mode.
  354. protocol_factory should instantiate object with Protocol interface.
  355. pipe is a file-like object.
  356. Return pair (transport, protocol), where transport supports the
  357. ReadTransport interface."""
  358. # The reason to accept file-like object instead of just file descriptor
  359. # is: we need to own pipe and close it at transport finishing
  360. # Can got complicated errors if pass f.fileno(),
  361. # close fd in pipe transport then close f and vice versa.
  362. raise NotImplementedError
  363. async def connect_write_pipe(self, protocol_factory, pipe):
  364. """Register write pipe in event loop.
  365. protocol_factory should instantiate object with BaseProtocol interface.
  366. Pipe is file-like object already switched to nonblocking.
  367. Return pair (transport, protocol), where transport support
  368. WriteTransport interface."""
  369. # The reason to accept file-like object instead of just file descriptor
  370. # is: we need to own pipe and close it at transport finishing
  371. # Can got complicated errors if pass f.fileno(),
  372. # close fd in pipe transport then close f and vice versa.
  373. raise NotImplementedError
  374. async def subprocess_shell(self, protocol_factory, cmd, *,
  375. stdin=subprocess.PIPE,
  376. stdout=subprocess.PIPE,
  377. stderr=subprocess.PIPE,
  378. **kwargs):
  379. raise NotImplementedError
  380. async def subprocess_exec(self, protocol_factory, *args,
  381. stdin=subprocess.PIPE,
  382. stdout=subprocess.PIPE,
  383. stderr=subprocess.PIPE,
  384. **kwargs):
  385. raise NotImplementedError
  386. # Ready-based callback registration methods.
  387. # The add_*() methods return None.
  388. # The remove_*() methods return True if something was removed,
  389. # False if there was nothing to delete.
  390. def add_reader(self, fd, callback, *args):
  391. raise NotImplementedError
  392. def remove_reader(self, fd):
  393. raise NotImplementedError
  394. def add_writer(self, fd, callback, *args):
  395. raise NotImplementedError
  396. def remove_writer(self, fd):
  397. raise NotImplementedError
  398. # Completion based I/O methods returning Futures.
  399. async def sock_recv(self, sock, nbytes):
  400. raise NotImplementedError
  401. async def sock_recv_into(self, sock, buf):
  402. raise NotImplementedError
  403. async def sock_sendall(self, sock, data):
  404. raise NotImplementedError
  405. async def sock_connect(self, sock, address):
  406. raise NotImplementedError
  407. async def sock_accept(self, sock):
  408. raise NotImplementedError
  409. async def sock_sendfile(self, sock, file, offset=0, count=None,
  410. *, fallback=None):
  411. raise NotImplementedError
  412. # Signal handling.
  413. def add_signal_handler(self, sig, callback, *args):
  414. raise NotImplementedError
  415. def remove_signal_handler(self, sig):
  416. raise NotImplementedError
  417. # Task factory.
  418. def set_task_factory(self, factory):
  419. raise NotImplementedError
  420. def get_task_factory(self):
  421. raise NotImplementedError
  422. # Error handlers.
  423. def get_exception_handler(self):
  424. raise NotImplementedError
  425. def set_exception_handler(self, handler):
  426. raise NotImplementedError
  427. def default_exception_handler(self, context):
  428. raise NotImplementedError
  429. def call_exception_handler(self, context):
  430. raise NotImplementedError
  431. # Debug flag management.
  432. def get_debug(self):
  433. raise NotImplementedError
  434. def set_debug(self, enabled):
  435. raise NotImplementedError
  436. class AbstractEventLoopPolicy:
  437. """Abstract policy for accessing the event loop."""
  438. def get_event_loop(self):
  439. """Get the event loop for the current context.
  440. Returns an event loop object implementing the BaseEventLoop interface,
  441. or raises an exception in case no event loop has been set for the
  442. current context and the current policy does not specify to create one.
  443. It should never return None."""
  444. raise NotImplementedError
  445. def set_event_loop(self, loop):
  446. """Set the event loop for the current context to loop."""
  447. raise NotImplementedError
  448. def new_event_loop(self):
  449. """Create and return a new event loop object according to this
  450. policy's rules. If there's need to set this loop as the event loop for
  451. the current context, set_event_loop must be called explicitly."""
  452. raise NotImplementedError
  453. # Child processes handling (Unix only).
  454. def get_child_watcher(self):
  455. "Get the watcher for child processes."
  456. raise NotImplementedError
  457. def set_child_watcher(self, watcher):
  458. """Set the watcher for child processes."""
  459. raise NotImplementedError
  460. class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
  461. """Default policy implementation for accessing the event loop.
  462. In this policy, each thread has its own event loop. However, we
  463. only automatically create an event loop by default for the main
  464. thread; other threads by default have no event loop.
  465. Other policies may have different rules (e.g. a single global
  466. event loop, or automatically creating an event loop per thread, or
  467. using some other notion of context to which an event loop is
  468. associated).
  469. """
  470. _loop_factory = None
  471. class _Local(threading.local):
  472. _loop = None
  473. _set_called = False
  474. def __init__(self):
  475. self._local = self._Local()
  476. def get_event_loop(self):
  477. """Get the event loop for the current context.
  478. Returns an instance of EventLoop or raises an exception.
  479. """
  480. if (self._local._loop is None and
  481. not self._local._set_called and
  482. threading.current_thread() is threading.main_thread()):
  483. self.set_event_loop(self.new_event_loop())
  484. if self._local._loop is None:
  485. raise RuntimeError('There is no current event loop in thread %r.'
  486. % threading.current_thread().name)
  487. return self._local._loop
  488. def set_event_loop(self, loop):
  489. """Set the event loop."""
  490. self._local._set_called = True
  491. assert loop is None or isinstance(loop, AbstractEventLoop)
  492. self._local._loop = loop
  493. def new_event_loop(self):
  494. """Create a new event loop.
  495. You must call set_event_loop() to make this the current event
  496. loop.
  497. """
  498. return self._loop_factory()
  499. # Event loop policy. The policy itself is always global, even if the
  500. # policy's rules say that there is an event loop per thread (or other
  501. # notion of context). The default policy is installed by the first
  502. # call to get_event_loop_policy().
  503. _event_loop_policy = None
  504. # Lock for protecting the on-the-fly creation of the event loop policy.
  505. _lock = threading.Lock()
  506. # A TLS for the running event loop, used by _get_running_loop.
  507. class _RunningLoop(threading.local):
  508. loop_pid = (None, None)
  509. _running_loop = _RunningLoop()
  510. def get_running_loop():
  511. """Return the running event loop. Raise a RuntimeError if there is none.
  512. This function is thread-specific.
  513. """
  514. # NOTE: this function is implemented in C (see _asynciomodule.c)
  515. loop = _get_running_loop()
  516. if loop is None:
  517. raise RuntimeError('no running event loop')
  518. return loop
  519. def _get_running_loop():
  520. """Return the running event loop or None.
  521. This is a low-level function intended to be used by event loops.
  522. This function is thread-specific.
  523. """
  524. # NOTE: this function is implemented in C (see _asynciomodule.c)
  525. running_loop, pid = _running_loop.loop_pid
  526. if running_loop is not None and pid == os.getpid():
  527. return running_loop
  528. def _set_running_loop(loop):
  529. """Set the running event loop.
  530. This is a low-level function intended to be used by event loops.
  531. This function is thread-specific.
  532. """
  533. # NOTE: this function is implemented in C (see _asynciomodule.c)
  534. _running_loop.loop_pid = (loop, os.getpid())
  535. def _init_event_loop_policy():
  536. global _event_loop_policy
  537. with _lock:
  538. if _event_loop_policy is None: # pragma: no branch
  539. from . import DefaultEventLoopPolicy
  540. _event_loop_policy = DefaultEventLoopPolicy()
  541. def get_event_loop_policy():
  542. """Get the current event loop policy."""
  543. if _event_loop_policy is None:
  544. _init_event_loop_policy()
  545. return _event_loop_policy
  546. def set_event_loop_policy(policy):
  547. """Set the current event loop policy.
  548. If policy is None, the default policy is restored."""
  549. global _event_loop_policy
  550. assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
  551. _event_loop_policy = policy
  552. def get_event_loop():
  553. """Return an asyncio event loop.
  554. When called from a coroutine or a callback (e.g. scheduled with call_soon
  555. or similar API), this function will always return the running event loop.
  556. If there is no running event loop set, the function will return
  557. the result of `get_event_loop_policy().get_event_loop()` call.
  558. """
  559. # NOTE: this function is implemented in C (see _asynciomodule.c)
  560. current_loop = _get_running_loop()
  561. if current_loop is not None:
  562. return current_loop
  563. return get_event_loop_policy().get_event_loop()
  564. def set_event_loop(loop):
  565. """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
  566. get_event_loop_policy().set_event_loop(loop)
  567. def new_event_loop():
  568. """Equivalent to calling get_event_loop_policy().new_event_loop()."""
  569. return get_event_loop_policy().new_event_loop()
  570. def get_child_watcher():
  571. """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
  572. return get_event_loop_policy().get_child_watcher()
  573. def set_child_watcher(watcher):
  574. """Equivalent to calling
  575. get_event_loop_policy().set_child_watcher(watcher)."""
  576. return get_event_loop_policy().set_child_watcher(watcher)
  577. # Alias pure-Python implementations for testing purposes.
  578. _py__get_running_loop = _get_running_loop
  579. _py__set_running_loop = _set_running_loop
  580. _py_get_running_loop = get_running_loop
  581. _py_get_event_loop = get_event_loop
  582. try:
  583. # get_event_loop() is one of the most frequently called
  584. # functions in asyncio. Pure Python implementation is
  585. # about 4 times slower than C-accelerated.
  586. from _asyncio import (_get_running_loop, _set_running_loop,
  587. get_running_loop, get_event_loop)
  588. except ImportError:
  589. pass
  590. else:
  591. # Alias C implementations for testing purposes.
  592. _c__get_running_loop = _get_running_loop
  593. _c__set_running_loop = _set_running_loop
  594. _c_get_running_loop = get_running_loop
  595. _c_get_event_loop = get_event_loop