events.py 28 KB

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