Sự kiện có nghĩa là gì trong Python?

Vòng lặp sự kiện là cốt lõi của mọi ứng dụng asyncio. Các vòng lặp sự kiện chạy các tác vụ và lệnh gọi lại không đồng bộ, thực hiện các hoạt động IO của mạng và chạy các quy trình con

Các nhà phát triển ứng dụng thường nên sử dụng các hàm asyncio cấp cao, chẳng hạn như và hiếm khi cần tham chiếu đối tượng vòng lặp hoặc gọi các phương thức của nó. Phần này chủ yếu dành cho các tác giả của mã, thư viện và khung cấp thấp hơn, những người cần kiểm soát tốt hơn đối với hành vi của vòng lặp sự kiện

Lấy vòng lặp sự kiện

Các chức năng cấp thấp sau đây có thể được sử dụng để lấy, đặt hoặc tạo một vòng lặp sự kiện

không đồng bộ. get_running_loop()

Trả về vòng lặp sự kiện đang chạy trong chuỗi hệ điều hành hiện tại

Tăng a nếu không có vòng lặp sự kiện đang chạy

Hàm này chỉ có thể được gọi từ coroutine hoặc callback

Mới trong phiên bản 3. 7

không đồng bộ. get_event_loop()

Nhận vòng lặp sự kiện hiện tại

Khi được gọi từ coroutine hoặc callback (e. g. được lên lịch với call_soon hoặc API tương tự), chức năng này sẽ luôn trả về vòng lặp sự kiện đang chạy

Nếu không có bộ vòng lặp sự kiện đang chạy, hàm sẽ trả về kết quả của lệnh gọi

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
2

Bởi vì chức năng này có hành vi khá phức tạp (đặc biệt là khi chính sách vòng lặp sự kiện tùy chỉnh đang được sử dụng), nên sử dụng chức năng này được ưa thích hơn trong coroutine và cuộc gọi lại

Như đã lưu ý ở trên, hãy cân nhắc sử dụng chức năng cấp cao hơn, thay vì sử dụng các chức năng cấp thấp hơn này để tạo và đóng vòng lặp sự kiện theo cách thủ công

Ghi chú

Trong Python phiên bản 3. 10. 0–3. 10. 8 và 3. 11. 0 chức năng này (và các chức năng khác sử dụng nó hoàn toàn) đã phát ra nếu không có vòng lặp sự kiện nào đang chạy, ngay cả khi vòng lặp hiện tại được đặt theo chính sách. Trong Python phiên bản 3. 10. 9, 3. 11. 1 và 3. 12 chúng phát ra nếu không có vòng lặp sự kiện đang chạy và không có vòng lặp hiện tại nào được đặt. Trong một số bản phát hành Python trong tương lai, điều này sẽ trở thành một lỗi

không đồng bộ. set_event_loop(vòng lặp)

Đặt vòng lặp làm vòng lặp sự kiện hiện tại cho chuỗi hệ điều hành hiện tại

không đồng bộ. new_event_loop()

Tạo và trả về một đối tượng vòng lặp sự kiện mới

Lưu ý rằng hành vi của , , và chức năng có thể được thay đổi bởi

Contents

Trang tài liệu này chứa các phần sau

  • Phần này là tài liệu tham khảo về API vòng lặp sự kiện;

  • The section documents the and instances which are returned from scheduling methods such as and ;

  • Các loại tài liệu phần được trả về từ các phương thức vòng lặp sự kiện như;

  • The section documents the and classes;

  • The section showcases how to work with some event loop APIs

Event Loop Methods

Event loops have low-level APIs for the following

loop. run_until_complete(future)

Run until the future (an instance of ) has completed

If the argument is a it is implicitly scheduled to run as a

Return the Future’s result or raise its exception

loop. run_forever()

Run the event loop until is called

If is called before is called, the loop will poll the I/O selector once with a timeout of zero, run all callbacks scheduled in response to I/O events (and those that were already scheduled), and then exit

If is called while is running, the loop will run the current batch of callbacks and then exit. Note that new callbacks scheduled by callbacks will not run in this case; instead, they will run the next time or is called

loop. stop()

Stop the event loop

loop. is_running()

Return

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7 if the event loop is currently running

loop. is_closed()

Trả lại

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7 nếu vòng lặp sự kiện đã đóng

loop. close()

Close the event loop

The loop must not be running when this function is called. Any pending callbacks will be discarded

This method clears all queues and shuts down the executor, but does not wait for the executor to finish

This method is idempotent and irreversible. No other methods should be called after the event loop is closed

coroutine loop. shutdown_asyncgens()

Schedule all currently open objects to close with an call. After calling this method, the event loop will issue a warning if a new asynchronous generator is iterated. This should be used to reliably finalize all scheduled asynchronous generators

Note that there is no need to call this function when is used

Example

try:
    loop.run_forever()
finally:
    loop.run_until_complete(loop.shutdown_asyncgens())
    loop.close()

New in version 3. 6

coroutine loop. shutdown_default_executor()

Schedule the closure of the default executor and wait for it to join all of the threads in the

async def client_connected(reader, writer):
    # Communicate with the client with
    # reader/writer streams.  For example:
    await reader.readline()

async def main(host, port):
    srv = await asyncio.start_server(
        client_connected, host, port)
    await srv.serve_forever()

asyncio.run(main('127.0.0.1', 0))
1. After calling this method, a will be raised if is called while using the default executor

Note that there is no need to call this function when is used

New in version 3. 9

loop. call_soon(callback , *args , context=None)

Schedule the callback to be called with args arguments at the next iteration of the event loop

Callbacks are called in the order in which they are registered. Each callback will be called exactly once

An optional keyword-only context argument allows specifying a custom for the callback to run in. The current context is used when no context is provided

An instance of is returned, which can be used later to cancel the callback

Phương pháp này không an toàn cho luồng

loop. call_soon_threadsafe(callback , *args , context=None)

A thread-safe variant of . Must be used to schedule callbacks from another thread

Raises if called on a loop that’s been closed. This can happen on a secondary thread when the main application is shutting down

See the section of the documentation

Changed in version 3. 7. The context keyword-only parameter was added. See PEP 567 for more details.

Ghi chú

Most scheduling functions don’t allow passing keyword arguments. To do that, use

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))

Using partial objects is usually more convenient than using lambdas, as asyncio can render partial objects better in debug and error messages

Event loop provides mechanisms to schedule callback functions to be called at some point in the future. Event loop uses monotonic clocks to track time

loop. call_later(delay , callback , *args , context=None)

Schedule callback to be called after the given delay number of seconds (can be either an int or a float)

An instance of is returned which can be used to cancel the callback

callback will be called exactly once. If two callbacks are scheduled for exactly the same time, the order in which they are called is undefined

The optional positional args will be passed to the callback when it is called. If you want the callback to be called with keyword arguments use

An optional keyword-only context argument allows specifying a custom for the callback to run in. The current context is used when no context is provided

Changed in version 3. 7. The context keyword-only parameter was added. See PEP 567 for more details.

Changed in version 3. 8. In Python 3. 7 and earlier with the default event loop implementation, the delay could not exceed one day. This has been fixed in Python 3. 8.

loop. call_at(when , callback , *args , context=None)

Schedule callback to be called at the given absolute timestamp when (an int or a float), using the same time reference as

This method’s behavior is the same as

An instance of is returned which can be used to cancel the callback

Changed in version 3. 7. The context keyword-only parameter was added. See PEP 567 for more details.

Changed in version 3. 8. In Python 3. 7 and earlier with the default event loop implementation, the difference between when and the current time could not exceed one day. Điều này đã được sửa trong Python 3. 8.

. thời gian()

Trả về thời gian hiện tại, dưới dạng một giá trị, theo đồng hồ đơn điệu bên trong của vòng lặp sự kiện

Ghi chú

Đã thay đổi trong phiên bản 3. 8. Trong Python 3. 7 và thời gian chờ sớm hơn (độ trễ tương đối hoặc thời điểm tuyệt đối) không được vượt quá một ngày. Điều này đã được sửa trong Python 3. 8.

Xem thêm

Chức năng

. tạo_tương lai()

Tạo một đối tượng được gắn vào vòng lặp sự kiện

Đây là cách ưa thích để tạo Futures trong asyncio. This lets third-party event loops provide alternative implementations of the Future object (with better performance or instrumentation)

Mới trong phiên bản 3. 5. 2

loop. create_task(coro , * , name=None , context=None)

Schedule the execution of coro. Return a object

Third-party event loops can use their own subclass of for interoperability. In this case, the result type is a subclass of

If the name argument is provided and not

import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
3, it is set as the name of the task using

An optional keyword-only context argument allows specifying a custom for the coro to run in. The current context copy is created when no context is provided

Changed in version 3. 8. Added the name parameter.

Changed in version 3. 11. Added the context parameter.

loop. set_task_factory(factory)

Set a task factory that will be used by

If factory is

import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
3 the default task factory will be set. Otherwise, factory must be a callable with the signature matching
import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
8, where loop is a reference to the active event loop, and coro is a coroutine object. The callable must return a -compatible object

loop. get_task_factory()

Return a task factory or

import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
3 if the default one is in use

coroutine loop. create_connection(protocol_factory , máy chủ=None, port=None, *, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, happy_eyeballs_delay=None, interleave=None)

Open a streaming transport connection to a given address specified by host and port

The socket family can be either or depending on host (or the family argument, if provided)

The socket type will be

protocol_factory must be a callable returning an implementation

This method will try to establish the connection in the background. When successful, it returns a

import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.new_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
4 pair

The chronological synopsis of the underlying operation is as follows

  1. Kết nối được thiết lập và a được tạo cho nó

  2. protocol_factory is called without arguments and is expected to return a instance

  3. The protocol instance is coupled with the transport by calling its method

  4. A

    import asyncio
    import datetime
    
    def display_date(end_time, loop):
        print(datetime.datetime.now())
        if (loop.time() + 1.0) < end_time:
            loop.call_later(1, display_date, end_time, loop)
        else:
            loop.stop()
    
    loop = asyncio.new_event_loop()
    
    # Schedule the first call to display_date()
    end_time = loop.time() + 5.0
    loop.call_soon(display_date, end_time, loop)
    
    # Blocking call interrupted by loop.stop()
    try:
        loop.run_forever()
    finally:
        loop.close()
    
    4 tuple is returned on success

The created transport is an implementation-dependent bidirectional stream

Other arguments

  • ssl. if given and not false, a SSL/TLS transport is created (by default a plain TCP transport is created). If ssl is a object, this context is used to create the transport; if ssl is , a default context returned from is used

    Xem thêm

  • server_hostname sets or overrides the hostname that the target server’s certificate will be matched against. Should only be passed if ssl is not

    import asyncio
    
    def hello_world(loop):
        """A callback to print 'Hello World' and stop the event loop"""
        print('Hello World')
        loop.stop()
    
    loop = asyncio.new_event_loop()
    
    # Schedule a call to hello_world()
    loop.call_soon(hello_world, loop)
    
    # Blocking call interrupted by loop.stop()
    try:
        loop.run_forever()
    finally:
        loop.close()
    
    3. By default the value of the host argument is used. If host is empty, there is no default and you must pass a value for server_hostname. If server_hostname is an empty string, hostname matching is disabled (which is a serious security risk, allowing for potential man-in-the-middle attacks)

  • family, proto, flags are the optional address family, protocol and flags to be passed through to getaddrinfo() for host resolution. If given, these should all be integers from the corresponding module constants

  • happy_eyeballs_delay, if given, enables Happy Eyeballs for this connection. It should be a floating-point number representing the amount of time in seconds to wait for a connection attempt to complete, before starting the next attempt in parallel. This is the “Connection Attempt Delay” as defined in RFC 8305. A sensible default value recommended by the RFC is

    import asyncio
    from socket import socketpair
    
    # Create a pair of connected file descriptors
    rsock, wsock = socketpair()
    
    loop = asyncio.new_event_loop()
    
    def reader():
        data = rsock.recv(100)
        print("Received:", data.decode())
    
        # We are done: unregister the file descriptor
        loop.remove_reader(rsock)
    
        # Stop the event loop
        loop.stop()
    
    # Register the file descriptor for read event
    loop.add_reader(rsock, reader)
    
    # Simulate the reception of data from the network
    loop.call_soon(wsock.send, 'abc'.encode())
    
    try:
        # Run the event loop
        loop.run_forever()
    finally:
        # We are done. Close sockets and the event loop.
        rsock.close()
        wsock.close()
        loop.close()
    
    2 (250 milliseconds)

  • interleave controls address reordering when a host name resolves to multiple IP addresses. If

    import asyncio
    from socket import socketpair
    
    # Create a pair of connected file descriptors
    rsock, wsock = socketpair()
    
    loop = asyncio.new_event_loop()
    
    def reader():
        data = rsock.recv(100)
        print("Received:", data.decode())
    
        # We are done: unregister the file descriptor
        loop.remove_reader(rsock)
    
        # Stop the event loop
        loop.stop()
    
    # Register the file descriptor for read event
    loop.add_reader(rsock, reader)
    
    # Simulate the reception of data from the network
    loop.call_soon(wsock.send, 'abc'.encode())
    
    try:
        # Run the event loop
        loop.run_forever()
    finally:
        # We are done. Close sockets and the event loop.
        rsock.close()
        wsock.close()
        loop.close()
    
    3 or unspecified, no reordering is done, and addresses are tried in the order returned by . If a positive integer is specified, the addresses are interleaved by address family, and the given integer is interpreted as “First Address Family Count” as defined in RFC 8305. The default is
    import asyncio
    from socket import socketpair
    
    # Create a pair of connected file descriptors
    rsock, wsock = socketpair()
    
    loop = asyncio.new_event_loop()
    
    def reader():
        data = rsock.recv(100)
        print("Received:", data.decode())
    
        # We are done: unregister the file descriptor
        loop.remove_reader(rsock)
    
        # Stop the event loop
        loop.stop()
    
    # Register the file descriptor for read event
    loop.add_reader(rsock, reader)
    
    # Simulate the reception of data from the network
    loop.call_soon(wsock.send, 'abc'.encode())
    
    try:
        # Run the event loop
        loop.run_forever()
    finally:
        # We are done. Close sockets and the event loop.
        rsock.close()
        wsock.close()
        loop.close()
    
    3 if happy_eyeballs_delay is not specified, and
    import asyncio
    from socket import socketpair
    
    # Create a pair of connected file descriptors
    rsock, wsock = socketpair()
    
    loop = asyncio.new_event_loop()
    
    def reader():
        data = rsock.recv(100)
        print("Received:", data.decode())
    
        # We are done: unregister the file descriptor
        loop.remove_reader(rsock)
    
        # Stop the event loop
        loop.stop()
    
    # Register the file descriptor for read event
    loop.add_reader(rsock, reader)
    
    # Simulate the reception of data from the network
    loop.call_soon(wsock.send, 'abc'.encode())
    
    try:
        # Run the event loop
        loop.run_forever()
    finally:
        # We are done. Close sockets and the event loop.
        rsock.close()
        wsock.close()
        loop.close()
    
    6 if it is

  • sock, if given, should be an existing, already connected object to be used by the transport. If sock is given, none of host, port, family, proto, flags, happy_eyeballs_delay, interleave and local_addr should be specified

    Ghi chú

    Đối số sock chuyển quyền sở hữu ổ cắm sang phương tiện vận chuyển được tạo. To close the socket, call the transport’s method

  • local_addr, if given, is a

    import asyncio
    from socket import socketpair
    
    # Create a pair of connected file descriptors
    rsock, wsock = socketpair()
    
    loop = asyncio.new_event_loop()
    
    def reader():
        data = rsock.recv(100)
        print("Received:", data.decode())
    
        # We are done: unregister the file descriptor
        loop.remove_reader(rsock)
    
        # Stop the event loop
        loop.stop()
    
    # Register the file descriptor for read event
    loop.add_reader(rsock, reader)
    
    # Simulate the reception of data from the network
    loop.call_soon(wsock.send, 'abc'.encode())
    
    try:
        # Run the event loop
        loop.run_forever()
    finally:
        # We are done. Close sockets and the event loop.
        rsock.close()
        wsock.close()
        loop.close()
    
    9 tuple used to bind the socket locally. The local_host and local_port are looked up using
    import asyncio
    from socket import socketpair
    
    # Create a pair of connected file descriptors
    rsock, wsock = socketpair()
    
    loop = asyncio.new_event_loop()
    
    def reader():
        data = rsock.recv(100)
        print("Received:", data.decode())
    
        # We are done: unregister the file descriptor
        loop.remove_reader(rsock)
    
        # Stop the event loop
        loop.stop()
    
    # Register the file descriptor for read event
    loop.add_reader(rsock, reader)
    
    # Simulate the reception of data from the network
    loop.call_soon(wsock.send, 'abc'.encode())
    
    try:
        # Run the event loop
        loop.run_forever()
    finally:
        # We are done. Close sockets and the event loop.
        rsock.close()
        wsock.close()
        loop.close()
    
    4, similarly to host and port

  • ssl_handshake_timeout is (for a TLS connection) the time in seconds to wait for the TLS handshake to complete before aborting the connection.

    import asyncio
    import functools
    import os
    import signal
    
    def ask_exit(signame, loop):
        print("got signal %s: exit" % signame)
        loop.stop()
    
    async def main():
        loop = asyncio.get_running_loop()
    
        for signame in {'SIGINT', 'SIGTERM'}:
            loop.add_signal_handler(
                getattr(signal, signame),
                functools.partial(ask_exit, signame, loop))
    
        await asyncio.sleep(3600)
    
    print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
    print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
    
    asyncio.run(main())
    
    1 seconds if
    import asyncio
    
    def hello_world(loop):
        """A callback to print 'Hello World' and stop the event loop"""
        print('Hello World')
        loop.stop()
    
    loop = asyncio.new_event_loop()
    
    # Schedule a call to hello_world()
    loop.call_soon(hello_world, loop)
    
    # Blocking call interrupted by loop.stop()
    try:
        loop.run_forever()
    finally:
        loop.close()
    
    3 (default)

  • ssl_shutdown_timeout is the time in seconds to wait for the SSL shutdown to complete before aborting the connection.

    import asyncio
    import functools
    import os
    import signal
    
    def ask_exit(signame, loop):
        print("got signal %s: exit" % signame)
        loop.stop()
    
    async def main():
        loop = asyncio.get_running_loop()
    
        for signame in {'SIGINT', 'SIGTERM'}:
            loop.add_signal_handler(
                getattr(signal, signame),
                functools.partial(ask_exit, signame, loop))
    
        await asyncio.sleep(3600)
    
    print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
    print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
    
    asyncio.run(main())
    
    3 seconds if
    import asyncio
    
    def hello_world(loop):
        """A callback to print 'Hello World' and stop the event loop"""
        print('Hello World')
        loop.stop()
    
    loop = asyncio.new_event_loop()
    
    # Schedule a call to hello_world()
    loop.call_soon(hello_world, loop)
    
    # Blocking call interrupted by loop.stop()
    try:
        loop.run_forever()
    finally:
        loop.close()
    
    3 (default)

Changed in version 3. 5. Added support for SSL/TLS in .

Changed in version 3. 6. The socket option

import asyncio
import functools
import os
import signal

def ask_exit(signame, loop):
    print("got signal %s: exit" % signame)
    loop.stop()

async def main():
    loop = asyncio.get_running_loop()

    for signame in {'SIGINT', 'SIGTERM'}:
        loop.add_signal_handler(
            getattr(signal, signame),
            functools.partial(ask_exit, signame, loop))

    await asyncio.sleep(3600)

print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")

asyncio.run(main())
6 is set by default for all TCP connections.

Changed in version 3. 7. Added the ssl_handshake_timeout parameter.

Changed in version 3. 8. Added the happy_eyeballs_delay and interleave parameters.

Happy Eyeballs Algorithm. Success with Dual-Stack Hosts. When a server’s IPv4 path and protocol are working, but the server’s IPv6 path and protocol are not working, a dual-stack client application experiences significant connection delay compared to an IPv4-only client. This is undesirable because it causes the dual- stack client to have a worse user experience. Tài liệu này chỉ định các yêu cầu đối với các thuật toán giúp giảm độ trễ mà người dùng có thể nhìn thấy này và cung cấp một thuật toán

Để biết thêm thông tin. https. //công cụ. vietf. org/html/rfc6555

Đã thay đổi trong phiên bản 3. 11. Đã thêm thông số ssl_shutdown_timeout.

Xem thêm

Chức năng này là một API thay thế cấp cao. Nó trả về một cặp (, ) có thể được sử dụng trực tiếp trong mã async/await

coroutine . create_datagram_endpoint(protocol_factory , local_addr=None, remote_addr=None, *, family=0, proto=0, flags=0, reuse_port=None, allow_broadcast=None, sock=None)

Tạo một kết nối datagram

Họ ổ cắm có thể là , , hoặc , tùy thuộc vào Máy chủ (hoặc đối số họ, nếu được cung cấp)

The socket type will be

protocol_factory phải có thể gọi được khi trả về một triển khai

Một bộ dữ liệu của

import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.new_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
4 được trả về khi thành công

Other arguments

  • local_addr, nếu được cung cấp, là một bộ dữ liệu

    import asyncio
    from socket import socketpair
    
    # Create a pair of connected file descriptors
    rsock, wsock = socketpair()
    
    loop = asyncio.new_event_loop()
    
    def reader():
        data = rsock.recv(100)
        print("Received:", data.decode())
    
        # We are done: unregister the file descriptor
        loop.remove_reader(rsock)
    
        # Stop the event loop
        loop.stop()
    
    # Register the file descriptor for read event
    loop.add_reader(rsock, reader)
    
    # Simulate the reception of data from the network
    loop.call_soon(wsock.send, 'abc'.encode())
    
    try:
        # Run the event loop
        loop.run_forever()
    finally:
        # We are done. Close sockets and the event loop.
        rsock.close()
        wsock.close()
        loop.close()
    
    9 được sử dụng để liên kết ổ cắm cục bộ. local_host và local_port được tra cứu bằng cách sử dụng

  • remote_addr, nếu được cung cấp, là một bộ dữ liệu

    # will schedule "print("Hello", flush=True)"
    loop.call_soon(
        functools.partial(print, "Hello", flush=True))
    
    07 được sử dụng để kết nối ổ cắm với một địa chỉ từ xa. remote_host và remote_port được tra cứu bằng cách sử dụng

  • họ, proto, cờ là họ địa chỉ, giao thức và cờ tùy chọn được chuyển qua để phân giải máy chủ. Nếu được cung cấp, tất cả những thứ này phải là số nguyên từ các hằng số mô-đun tương ứng

  • tái sử dụng_port yêu cầu kernel cho phép điểm cuối này được liên kết với cùng một cổng như các điểm cuối hiện có khác được liên kết, miễn là tất cả chúng đều đặt cờ này khi được tạo. Tùy chọn này không được hỗ trợ trên Windows và một số Unix. Nếu hằng số

    # will schedule "print("Hello", flush=True)"
    loop.call_soon(
        functools.partial(print, "Hello", flush=True))
    
    11 không được xác định thì khả năng này không được hỗ trợ

  • allow_broadcast yêu cầu kernel cho phép điểm cuối này gửi tin nhắn đến địa chỉ quảng bá

  • sock có thể được chỉ định tùy chọn để sử dụng một đối tượng có sẵn, đã được kết nối, được sử dụng bởi phương tiện vận chuyển. Nếu được chỉ định, nên bỏ qua local_addr và remote_addr (phải là )

    Ghi chú

    Đối số sock chuyển quyền sở hữu ổ cắm sang phương tiện vận chuyển được tạo. To close the socket, call the transport’s method

Xem và ví dụ

Đã thay đổi trong phiên bản 3. 4. 4. Các thông số gia đình, proto, cờ, tái sử dụng_địa chỉ, tái sử dụng_port, allow_broadcast và sock đã được thêm vào.

Đã thay đổi trong phiên bản 3. 8. 1. Tham sốReuse_address không còn được hỗ trợ vì việc sử dụng

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
15 gây ra mối lo ngại đáng kể về bảo mật cho UDP. Vượt qua rõ ràng
# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
16 sẽ đưa ra một ngoại lệ.

Khi nhiều quy trình có UID khác nhau gán các ổ cắm cho một địa chỉ ổ cắm UDP giống hệt nhau với

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
15, các gói đến có thể được phân phối ngẫu nhiên giữa các ổ cắm

Đối với các nền tảng được hỗ trợ, có thể sử dụnguse_port để thay thế cho chức năng tương tự. Với tái sử dụng_port, thay vào đó,

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
11 được sử dụng, điều này đặc biệt ngăn các quy trình có UID khác nhau gán ổ cắm cho cùng một địa chỉ ổ cắm

Đã thay đổi trong phiên bản 3. 8. Đã thêm hỗ trợ cho Windows.

Đã thay đổi trong phiên bản 3. 11. Tham sốReuse_address, bị vô hiệu hóa kể từ Python 3. 9. 0, 3. 8. 1, 3. 7. 6 và 3. 6. 10, đã bị xóa hoàn toàn.

coroutine . create_unix_connection(protocol_factory , đường dẫn=None, *, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)

Tạo kết nối Unix

Họ ổ cắm sẽ là ;

Một bộ dữ liệu của

import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.new_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
4 được trả về khi thành công

đường dẫn là tên của ổ cắm miền Unix và được yêu cầu, trừ khi tham số sock được chỉ định. Các socket, , và đường dẫn Unix trừu tượng được hỗ trợ

Xem tài liệu của phương thức để biết thông tin về các đối số của phương thức này

Unix

Đã thay đổi trong phiên bản 3. 7. Đã thêm tham số ssl_handshake_timeout. Tham số đường dẫn bây giờ có thể là một.

Đã thay đổi trong phiên bản 3. 11. Đã thêm thông số ssl_shutdown_timeout.

coroutine . create_server(protocol_factory , máy chủ . AF_UNSPEC=None, port=None, *, family=socket.AF_UNSPEC , cờ=ổ cắm. AI_PASSIVE , tất=Không có, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True)

Tạo một máy chủ TCP (loại ổ cắm) lắng nghe trên cổng của địa chỉ máy chủ

Trả về một đối tượng

Tranh luận

  • protocol_factory phải có thể gọi được khi trả về một triển khai

  • Tham số máy chủ có thể được đặt thành một số loại xác định nơi máy chủ sẽ lắng nghe

    • Nếu máy chủ là một chuỗi, máy chủ TCP được liên kết với một giao diện mạng duy nhất được chỉ định bởi máy chủ

    • Nếu máy chủ là một chuỗi các chuỗi, máy chủ TCP được liên kết với tất cả các giao diện mạng được chỉ định bởi chuỗi

    • Nếu máy chủ lưu trữ là một chuỗi trống hoặc

      import asyncio
      
      def hello_world(loop):
          """A callback to print 'Hello World' and stop the event loop"""
          print('Hello World')
          loop.stop()
      
      loop = asyncio.new_event_loop()
      
      # Schedule a call to hello_world()
      loop.call_soon(hello_world, loop)
      
      # Blocking call interrupted by loop.stop()
      try:
          loop.run_forever()
      finally:
          loop.close()
      
      3, tất cả các giao diện được giả định và một danh sách nhiều ổ cắm sẽ được trả về (rất có thể là một ổ cắm cho IPv4 và một ổ cắm khác cho IPv6)

  • Tham số cổng có thể được đặt để chỉ định máy chủ sẽ nghe trên cổng nào. Nếu

    import asyncio
    from socket import socketpair
    
    # Create a pair of connected file descriptors
    rsock, wsock = socketpair()
    
    loop = asyncio.new_event_loop()
    
    def reader():
        data = rsock.recv(100)
        print("Received:", data.decode())
    
        # We are done: unregister the file descriptor
        loop.remove_reader(rsock)
    
        # Stop the event loop
        loop.stop()
    
    # Register the file descriptor for read event
    loop.add_reader(rsock, reader)
    
    # Simulate the reception of data from the network
    loop.call_soon(wsock.send, 'abc'.encode())
    
    try:
        # Run the event loop
        loop.run_forever()
    finally:
        # We are done. Close sockets and the event loop.
        rsock.close()
        wsock.close()
        loop.close()
    
    3 hoặc
    import asyncio
    
    def hello_world(loop):
        """A callback to print 'Hello World' and stop the event loop"""
        print('Hello World')
        loop.stop()
    
    loop = asyncio.new_event_loop()
    
    # Schedule a call to hello_world()
    loop.call_soon(hello_world, loop)
    
    # Blocking call interrupted by loop.stop()
    try:
        loop.run_forever()
    finally:
        loop.close()
    
    3 (mặc định), một cổng ngẫu nhiên không sử dụng sẽ được chọn (lưu ý rằng nếu máy chủ phân giải thành nhiều giao diện mạng, một cổng ngẫu nhiên khác sẽ được chọn cho mỗi giao diện)

  • gia đình có thể được đặt thành hoặc để buộc ổ cắm sử dụng IPv4 hoặc IPv6. Nếu không được đặt, họ sẽ được xác định từ tên máy chủ (mặc định là

    # will schedule "print("Hello", flush=True)"
    loop.call_soon(
        functools.partial(print, "Hello", flush=True))
    
    33)

  • cờ là một bitmask cho

  • sock có thể được chỉ định tùy chọn để sử dụng đối tượng ổ cắm có sẵn. Nếu được chỉ định, máy chủ và cổng không được chỉ định

    Ghi chú

    Đối số sock chuyển quyền sở hữu ổ cắm cho máy chủ được tạo. Để đóng socket, hãy gọi phương thức của máy chủ

  • tồn đọng là số lượng kết nối hàng đợi tối đa được chuyển đến (mặc định là 100)

  • ssl có thể được đặt thành một phiên bản để bật TLS qua các kết nối được chấp nhận

  • reuse_address tells the kernel to reuse a local socket in

    # will schedule "print("Hello", flush=True)"
    loop.call_soon(
        functools.partial(print, "Hello", flush=True))
    
    38 state, without waiting for its natural timeout to expire. Nếu không được chỉ định sẽ tự động được đặt thành
    srv = await loop.create_server(...)
    
    async with srv:
        # some code
    
    # At this point, srv is closed and no longer accepts new connections.
    
    7 trên Unix

  • tái sử dụng_port yêu cầu kernel cho phép điểm cuối này được liên kết với cùng một cổng như các điểm cuối hiện có khác được liên kết, miễn là tất cả chúng đều đặt cờ này khi được tạo. Tùy chọn này không được hỗ trợ trên Windows

  • ssl_handshake_timeout là (đối với máy chủ TLS) thời gian tính bằng giây để đợi quá trình bắt tay TLS hoàn tất trước khi hủy kết nối.

    import asyncio
    import functools
    import os
    import signal
    
    def ask_exit(signame, loop):
        print("got signal %s: exit" % signame)
        loop.stop()
    
    async def main():
        loop = asyncio.get_running_loop()
    
        for signame in {'SIGINT', 'SIGTERM'}:
            loop.add_signal_handler(
                getattr(signal, signame),
                functools.partial(ask_exit, signame, loop))
    
        await asyncio.sleep(3600)
    
    print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
    print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
    
    asyncio.run(main())
    
    1 giây nếu
    import asyncio
    
    def hello_world(loop):
        """A callback to print 'Hello World' and stop the event loop"""
        print('Hello World')
        loop.stop()
    
    loop = asyncio.new_event_loop()
    
    # Schedule a call to hello_world()
    loop.call_soon(hello_world, loop)
    
    # Blocking call interrupted by loop.stop()
    try:
        loop.run_forever()
    finally:
        loop.close()
    
    3 (mặc định)

  • ssl_shutdown_timeout is the time in seconds to wait for the SSL shutdown to complete before aborting the connection.

    import asyncio
    import functools
    import os
    import signal
    
    def ask_exit(signame, loop):
        print("got signal %s: exit" % signame)
        loop.stop()
    
    async def main():
        loop = asyncio.get_running_loop()
    
        for signame in {'SIGINT', 'SIGTERM'}:
            loop.add_signal_handler(
                getattr(signal, signame),
                functools.partial(ask_exit, signame, loop))
    
        await asyncio.sleep(3600)
    
    print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
    print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
    
    asyncio.run(main())
    
    3 seconds if
    import asyncio
    
    def hello_world(loop):
        """A callback to print 'Hello World' and stop the event loop"""
        print('Hello World')
        loop.stop()
    
    loop = asyncio.new_event_loop()
    
    # Schedule a call to hello_world()
    loop.call_soon(hello_world, loop)
    
    # Blocking call interrupted by loop.stop()
    try:
        loop.run_forever()
    finally:
        loop.close()
    
    3 (default)

  • start_serving được đặt thành

    srv = await loop.create_server(...)
    
    async with srv:
        # some code
    
    # At this point, srv is closed and no longer accepts new connections.
    
    7 (mặc định) khiến máy chủ được tạo bắt đầu chấp nhận kết nối ngay lập tức. Khi được đặt thành
    # will schedule "print("Hello", flush=True)"
    loop.call_soon(
        functools.partial(print, "Hello", flush=True))
    
    45, người dùng nên chờ hoặc bắt máy chủ bắt đầu chấp nhận kết nối

Changed in version 3. 5. Added support for SSL/TLS in .

Đã thay đổi trong phiên bản 3. 5. 1. Tham số máy chủ có thể là một chuỗi các chuỗi.

Đã thay đổi trong phiên bản 3. 6. Đã thêm tham số ssl_handshake_timeout và start_serving. Tùy chọn ổ cắm

import asyncio
import functools
import os
import signal

def ask_exit(signame, loop):
    print("got signal %s: exit" % signame)
    loop.stop()

async def main():
    loop = asyncio.get_running_loop()

    for signame in {'SIGINT', 'SIGTERM'}:
        loop.add_signal_handler(
            getattr(signal, signame),
            functools.partial(ask_exit, signame, loop))

    await asyncio.sleep(3600)

print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")

asyncio.run(main())
6 được đặt theo mặc định cho tất cả các kết nối TCP.

Đã thay đổi trong phiên bản 3. 11. Đã thêm thông số ssl_shutdown_timeout.

Xem thêm

Hàm này là API thay thế cấp cao hơn trả về một cặp và có thể được sử dụng trong mã không đồng bộ/đang chờ

coroutine . create_unix_server(protocol_factory , đường dẫn=None, *, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None, start_serving=True)

Tương tự nhưng hoạt động với họ ổ cắm

đường dẫn là tên của ổ cắm tên miền Unix và là bắt buộc, trừ khi cung cấp đối số sock. Các socket, , và đường dẫn Unix trừu tượng được hỗ trợ

Xem tài liệu của phương thức để biết thông tin về các đối số của phương thức này

Unix

Đã thay đổi trong phiên bản 3. 7. Đã thêm thông số ssl_handshake_timeout và start_serving. Tham số đường dẫn bây giờ có thể là một đối tượng.

Đã thay đổi trong phiên bản 3. 11. Đã thêm thông số ssl_shutdown_timeout.

coroutine . connect_accepted_socket(protocol_factory , sock, *, ssl=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)

Bọc một kết nối đã được chấp nhận thành một cặp giao thức/truyền tải

Phương pháp này có thể được sử dụng bởi các máy chủ chấp nhận các kết nối bên ngoài asyncio nhưng sử dụng asyncio để xử lý chúng

Thông số

  • protocol_factory phải có thể gọi được khi trả về một triển khai

  • sock là một đối tượng ổ cắm có sẵn được trả về từ

    Ghi chú

    Đối số sock chuyển quyền sở hữu ổ cắm sang phương tiện vận chuyển được tạo. To close the socket, call the transport’s method

  • ssl có thể được đặt thành để bật SSL qua các kết nối được chấp nhận

  • ssl_handshake_timeout là (đối với kết nối SSL) thời gian tính bằng giây để đợi quá trình bắt tay SSL hoàn tất trước khi hủy kết nối.

    import asyncio
    import functools
    import os
    import signal
    
    def ask_exit(signame, loop):
        print("got signal %s: exit" % signame)
        loop.stop()
    
    async def main():
        loop = asyncio.get_running_loop()
    
        for signame in {'SIGINT', 'SIGTERM'}:
            loop.add_signal_handler(
                getattr(signal, signame),
                functools.partial(ask_exit, signame, loop))
    
        await asyncio.sleep(3600)
    
    print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
    print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
    
    asyncio.run(main())
    
    1 giây nếu
    import asyncio
    
    def hello_world(loop):
        """A callback to print 'Hello World' and stop the event loop"""
        print('Hello World')
        loop.stop()
    
    loop = asyncio.new_event_loop()
    
    # Schedule a call to hello_world()
    loop.call_soon(hello_world, loop)
    
    # Blocking call interrupted by loop.stop()
    try:
        loop.run_forever()
    finally:
        loop.close()
    
    3 (mặc định)

  • ssl_shutdown_timeout is the time in seconds to wait for the SSL shutdown to complete before aborting the connection.

    import asyncio
    import functools
    import os
    import signal
    
    def ask_exit(signame, loop):
        print("got signal %s: exit" % signame)
        loop.stop()
    
    async def main():
        loop = asyncio.get_running_loop()
    
        for signame in {'SIGINT', 'SIGTERM'}:
            loop.add_signal_handler(
                getattr(signal, signame),
                functools.partial(ask_exit, signame, loop))
    
        await asyncio.sleep(3600)
    
    print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
    print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
    
    asyncio.run(main())
    
    3 seconds if
    import asyncio
    
    def hello_world(loop):
        """A callback to print 'Hello World' and stop the event loop"""
        print('Hello World')
        loop.stop()
    
    loop = asyncio.new_event_loop()
    
    # Schedule a call to hello_world()
    loop.call_soon(hello_world, loop)
    
    # Blocking call interrupted by loop.stop()
    try:
        loop.run_forever()
    finally:
        loop.close()
    
    3 (default)

Trả về một cặp

import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.new_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
4

Mới trong phiên bản 3. 5. 3

Changed in version 3. 7. Added the ssl_handshake_timeout parameter.

Đã thay đổi trong phiên bản 3. 11. Đã thêm thông số ssl_shutdown_timeout.

coroutine . gửi tệp(vận chuyển , tệp, offset=0, count=None, *, fallback=True)

Gửi tệp qua phương tiện giao thông. Trả về tổng số byte đã gửi

Phương pháp sử dụng hiệu năng cao nếu có

tệp phải là đối tượng tệp thông thường được mở ở chế độ nhị phân

offset cho biết bắt đầu đọc tệp từ đâu. Nếu được chỉ định, số đếm là tổng số byte cần truyền thay vì gửi tệp cho đến khi đạt đến EOF. Vị trí tệp luôn được cập nhật, ngay cả khi phương pháp này phát sinh lỗi và có thể được sử dụng để lấy số byte thực tế đã gửi

dự phòng được đặt thành

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7 khiến asyncio đọc và gửi tệp theo cách thủ công khi nền tảng không hỗ trợ lệnh gọi hệ thống gửi tệp (e. g. Ổ cắm Windows hoặc SSL trên Unix)

Tăng nếu hệ thống không hỗ trợ tòa nhà tòa nhà sendfile và dự phòng là

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
45

Mới trong phiên bản 3. 7

coroutine . start_tls(vận chuyển , giao thức, sslcontext, *, server_side=False, server_hostname=None, ssl_handshake_timeout=None, ssl_shutdown_timeout=None)

Nâng cấp kết nối dựa trên giao thông hiện có lên TLS

Tạo một phiên bản bộ mã hóa/giải mã TLS và chèn nó vào giữa phương tiện truyền tải và giao thức. Bộ mã hóa/giải mã thực hiện cả giao thức truyền tải và truyền tải theo giao thức

Trả về phiên bản hai giao diện đã tạo. Sau khi chờ đợi, giao thức phải ngừng sử dụng phương thức truyền tải ban đầu và chỉ giao tiếp với đối tượng được trả về vì bộ mã hóa lưu trữ dữ liệu phía giao thức và trao đổi không thường xuyên các gói phiên TLS bổ sung với phương thức truyền tải

Thông số

  • các thể hiện vận chuyển và giao thức mà các phương thức thích và trả về

  • sslcontext. a configured instance of

  • server_side vượt qua

    srv = await loop.create_server(...)
    
    async with srv:
        # some code
    
    # At this point, srv is closed and no longer accepts new connections.
    
    7 khi kết nối phía máy chủ đang được nâng cấp (như kết nối được tạo bởi )

  • máy chủ_hostname. đặt hoặc ghi đè tên máy chủ mà chứng chỉ của máy chủ đích sẽ được khớp với

  • ssl_handshake_timeout is (for a TLS connection) the time in seconds to wait for the TLS handshake to complete before aborting the connection.

    import asyncio
    import functools
    import os
    import signal
    
    def ask_exit(signame, loop):
        print("got signal %s: exit" % signame)
        loop.stop()
    
    async def main():
        loop = asyncio.get_running_loop()
    
        for signame in {'SIGINT', 'SIGTERM'}:
            loop.add_signal_handler(
                getattr(signal, signame),
                functools.partial(ask_exit, signame, loop))
    
        await asyncio.sleep(3600)
    
    print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
    print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
    
    asyncio.run(main())
    
    1 seconds if
    import asyncio
    
    def hello_world(loop):
        """A callback to print 'Hello World' and stop the event loop"""
        print('Hello World')
        loop.stop()
    
    loop = asyncio.new_event_loop()
    
    # Schedule a call to hello_world()
    loop.call_soon(hello_world, loop)
    
    # Blocking call interrupted by loop.stop()
    try:
        loop.run_forever()
    finally:
        loop.close()
    
    3 (default)

  • ssl_shutdown_timeout is the time in seconds to wait for the SSL shutdown to complete before aborting the connection.

    import asyncio
    import functools
    import os
    import signal
    
    def ask_exit(signame, loop):
        print("got signal %s: exit" % signame)
        loop.stop()
    
    async def main():
        loop = asyncio.get_running_loop()
    
        for signame in {'SIGINT', 'SIGTERM'}:
            loop.add_signal_handler(
                getattr(signal, signame),
                functools.partial(ask_exit, signame, loop))
    
        await asyncio.sleep(3600)
    
    print("Event loop running for 1 hour, press Ctrl+C to interrupt.")
    print(f"pid {os.getpid()}: send SIGINT or SIGTERM to exit.")
    
    asyncio.run(main())
    
    3 seconds if
    import asyncio
    
    def hello_world(loop):
        """A callback to print 'Hello World' and stop the event loop"""
        print('Hello World')
        loop.stop()
    
    loop = asyncio.new_event_loop()
    
    # Schedule a call to hello_world()
    loop.call_soon(hello_world, loop)
    
    # Blocking call interrupted by loop.stop()
    try:
        loop.run_forever()
    finally:
        loop.close()
    
    3 (default)

Mới trong phiên bản 3. 7

Đã thay đổi trong phiên bản 3. 11. Đã thêm thông số ssl_shutdown_timeout.

. add_reader(fd , gọi lại, *args)

Bắt đầu theo dõi bộ mô tả tệp fd để biết khả năng đọc và gọi lại cuộc gọi với các đối số được chỉ định sau khi fd khả dụng để đọc

. remove_reader(fd)

Dừng theo dõi bộ mô tả tệp fd để biết tính sẵn sàng đọc. Trả về

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7 nếu fd trước đó được theo dõi để đọc

. add_writer(fd , gọi lại, *args)

Bắt đầu theo dõi bộ mô tả tệp fd để biết khả năng ghi và gọi hàm gọi lại với các đối số đã chỉ định khi fd sẵn sàng để ghi

Sử dụng để gọi lại

. remove_writer(fd)

Dừng theo dõi bộ mô tả tệp fd để ghi tính khả dụng. Trả về

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7 nếu trước đó fd được theo dõi để ghi

Xem thêm phần để biết một số hạn chế của các phương pháp này

Nói chung, việc triển khai giao thức sử dụng API dựa trên vận chuyển chẳng hạn như và nhanh hơn so với việc triển khai hoạt động trực tiếp với ổ cắm. Tuy nhiên, có một số trường hợp sử dụng khi hiệu suất không quan trọng và làm việc trực tiếp với các đối tượng sẽ thuận tiện hơn

coroutine . sock_recv(sock , nbyte)

Nhận tới nbyte từ sock. Phiên bản không đồng bộ của

Trả lại dữ liệu đã nhận dưới dạng đối tượng byte

sock phải là ổ cắm non-blocking

Đã thay đổi trong phiên bản 3. 7. Mặc dù phương thức này luôn được ghi lại dưới dạng phương thức coroutine, nhưng vẫn phát hành trước Python 3. 7 trả lại một. Kể từ Python 3. 7 đây là một phương pháp

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
90.

coroutine . sock_recv_into(sock , buf)

Nhận dữ liệu từ sock vào bộ đệm buf. Được mô phỏng theo phương pháp chặn

Trả về số byte được ghi vào bộ đệm

sock phải là ổ cắm non-blocking

Mới trong phiên bản 3. 7

coroutine . sock_recvfrom(sock , bufsize)

Nhận một datagram có kích thước tối đa từ sock. Phiên bản không đồng bộ của

Trả về một bộ dữ liệu (dữ liệu đã nhận, địa chỉ từ xa)

sock phải là ổ cắm non-blocking

Mới trong phiên bản 3. 11

coroutine . sock_recvfrom_into(sock , buf, nbytes=0)

Nhận một datagram lên đến nbyte từ sock vào buf. Phiên bản không đồng bộ của

Trả về một bộ (số byte nhận được, địa chỉ từ xa)

sock phải là ổ cắm non-blocking

Mới trong phiên bản 3. 11

coroutine . sock_sendall(sock , dữ liệu)

Gửi dữ liệu đến ổ cắm sock. Phiên bản không đồng bộ của

Phương pháp này tiếp tục gửi đến ổ cắm cho đến khi tất cả dữ liệu trong dữ liệu đã được gửi hoặc xảy ra lỗi.

import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
3 được trả lại khi thành công. Khi có lỗi, một ngoại lệ được đưa ra. Ngoài ra, không có cách nào để xác định lượng dữ liệu, nếu có, đã được xử lý thành công bởi đầu nhận của kết nối

sock phải là ổ cắm non-blocking

Đã thay đổi trong phiên bản 3. 7. Even though the method was always documented as a coroutine method, before Python 3. 7 nó trả về một. Kể từ Python 3. 7, đây là một phương pháp

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
90.

coroutine . sock_sendto(sock , dữ liệu, address)

Gửi một datagram từ vớ đến địa chỉ. Phiên bản không đồng bộ của

Trả về số byte đã gửi

sock phải là ổ cắm non-blocking

Mới trong phiên bản 3. 11

coroutine . sock_connect(sock , địa chỉ)

Kết nối tất với ổ cắm từ xa tại địa chỉ

Phiên bản không đồng bộ của

sock phải là ổ cắm non-blocking

Đã thay đổi trong phiên bản 3. 5. 2. ______63_______00 không cần giải quyết nữa.

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

if __name__ == '__main__':
    asyncio.run(main())
01 sẽ cố gắng kiểm tra xem địa chỉ đã được giải quyết chưa bằng cách gọi. Nếu không, sẽ được sử dụng để giải quyết địa chỉ.

Xem thêm

coroutine . sock_accept(sock)

Chấp nhận kết nối. Được mô phỏng theo phương pháp chặn

Ổ cắm phải được liên kết với một địa chỉ và lắng nghe các kết nối. Giá trị trả về là một cặp

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

if __name__ == '__main__':
    asyncio.run(main())
07 trong đó conn là một đối tượng ổ cắm mới có thể sử dụng để gửi và nhận dữ liệu trên kết nối và địa chỉ là địa chỉ được liên kết với ổ cắm ở đầu kia của kết nối

sock phải là ổ cắm non-blocking

Đã thay đổi trong phiên bản 3. 7. Even though the method was always documented as a coroutine method, before Python 3. 7 nó trả về một. Kể từ Python 3. 7, đây là một phương pháp

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
90.

Xem thêm

coroutine . sock_sendfile(sock , file, offset=0, count=None, *, fallback=True)

Gửi tệp bằng hiệu suất cao nếu có thể. Trả về tổng số byte đã gửi

Phiên bản không đồng bộ của

sock phải là một non-blocking

tệp phải là đối tượng tệp thông thường mở ở chế độ nhị phân

offset cho biết bắt đầu đọc tệp từ đâu. Nếu được chỉ định, số đếm là tổng số byte cần truyền thay vì gửi tệp cho đến khi đạt đến EOF. Vị trí tệp luôn được cập nhật, ngay cả khi phương pháp này phát sinh lỗi và có thể được sử dụng để lấy số byte thực tế đã gửi

dự phòng, khi được đặt thành

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7, làm cho asyncio đọc và gửi tệp theo cách thủ công khi nền tảng không hỗ trợ tòa nhà tòa nhà sendfile (e. g. Ổ cắm Windows hoặc SSL trên Unix)

Tăng nếu hệ thống không hỗ trợ tòa nhà tòa nhà sendfile và dự phòng là

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
45

sock phải là ổ cắm non-blocking

Mới trong phiên bản 3. 7

coroutine . getaddrinfo(máy chủ , cổng, *, family=0, type=0, proto=0, flags=0)

Phiên bản không đồng bộ của

coroutine . getnameinfo(sockaddr , cờ=0)

Phiên bản không đồng bộ của

Đã thay đổi trong phiên bản 3. 7. Cả hai phương thức getaddrinfo và getnameinfo luôn được ghi lại để trả về một coroutine, nhưng trước Python 3. 7 trên thực tế, họ đã trả lại các đối tượng. Bắt đầu với Python 3. 7 cả hai phương thức đều là coroutines.

coroutine . connect_read_pipe(protocol_factory , pipe)

Đăng ký đầu đọc của đường ống trong vòng lặp sự kiện

protocol_factory must be a callable returning an implementation

ống là một

Cặp trả về

import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.new_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
4, trong đó vận chuyển hỗ trợ giao diện và giao thức là một đối tượng được khởi tạo bởi giao thức_factory

Với vòng lặp sự kiện, đường ống được đặt ở chế độ không chặn

coroutine . connect_write_pipe(protocol_factory , pipe)

Đăng ký ghi cuối đường ống trong vòng lặp sự kiện

protocol_factory must be a callable returning an implementation

đường ống là

Cặp trả về

import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.new_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
4, trong đó giao diện và giao thức hỗ trợ vận chuyển là một đối tượng được khởi tạo bởi giao thức_factory

Với vòng lặp sự kiện, đường ống được đặt ở chế độ không chặn

Ghi chú

không hỗ trợ các phương pháp trên trên Windows. Sử dụng thay thế cho Windows

Xem thêm

Các và phương pháp

. add_signal_handler(signum , callback , *args)

Đặt gọi lại làm trình xử lý cho tín hiệu signum

Cuộc gọi lại sẽ được gọi theo vòng lặp, cùng với các cuộc gọi lại được xếp hàng đợi khác và các coroutine có thể chạy được của vòng lặp sự kiện đó. Không giống như các trình xử lý tín hiệu đã đăng ký bằng cách sử dụng, một cuộc gọi lại đã đăng ký với chức năng này được phép tương tác với vòng lặp sự kiện

Tăng nếu số tín hiệu không hợp lệ hoặc không bắt được. Nâng cao nếu có sự cố khi thiết lập trình xử lý

Sử dụng để gọi lại

Giống như, chức năng này phải được gọi trong luồng chính

. remove_signal_handler(sig)

Xóa trình xử lý cho tín hiệu sig

Trả lại

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7 nếu bộ xử lý tín hiệu đã bị xóa hoặc
# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
45 nếu không có bộ xử lý nào được đặt cho tín hiệu đã cho

Unix

Xem thêm

mô-đun

awaitable . run_in_executor(executor , func, *args)

Sắp xếp để func được gọi trong trình thực thi được chỉ định

Đối số thực thi phải là một thể hiện. Người thi hành mặc định được sử dụng nếu người thi hành là

import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
3

Example

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

if __name__ == '__main__':
    asyncio.run(main())

Lưu ý rằng bộ phận bảo vệ điểm vào (

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

if __name__ == '__main__':
    asyncio.run(main())
43) là bắt buộc đối với tùy chọn 3 do đặc thù của , được sử dụng bởi. Nhìn thấy

Phương thức này trả về một đối tượng

Sử dụng để giải trí

Đã thay đổi trong phiên bản 3. 5. 3. không còn định cấu hình

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

if __name__ == '__main__':
    asyncio.run(main())
49 của bộ thực thi nhóm luồng mà nó tạo ra, thay vào đó hãy để bộ thực thi nhóm luồng () đặt mặc định.

. set_default_executor(executor)

Đặt người thi hành làm người thi hành mặc định được sử dụng bởi. người thi hành phải là một thể hiện của

Đã thay đổi trong phiên bản 3. 11. executor phải là một thể hiện của.

Cho phép tùy chỉnh cách xử lý ngoại lệ trong vòng lặp sự kiện

. set_exception_handler(trình xử lý)

Đặt trình xử lý làm trình xử lý ngoại lệ vòng lặp sự kiện mới

Nếu trình xử lý là

import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
3, thì trình xử lý ngoại lệ mặc định sẽ được đặt. Mặt khác, trình xử lý phải có thể gọi được với chữ ký khớp với
import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

if __name__ == '__main__':
    asyncio.run(main())
55, trong đó
import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

if __name__ == '__main__':
    asyncio.run(main())
56 là tham chiếu đến vòng lặp sự kiện đang hoạt động và
import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

if __name__ == '__main__':
    asyncio.run(main())
57 là đối tượng
import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

if __name__ == '__main__':
    asyncio.run(main())
58 chứa thông tin chi tiết về ngoại lệ (xem tài liệu để biết chi tiết về ngữ cảnh)

. get_Exception_handler()

Trả về trình xử lý ngoại lệ hiện tại hoặc

import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
3 nếu không có trình xử lý ngoại lệ tùy chỉnh nào được đặt

Mới trong phiên bản 3. 5. 2

. default_exception_handler(bối cảnh)

Trình xử lý ngoại lệ mặc định

Điều này được gọi khi một ngoại lệ xảy ra và không có trình xử lý ngoại lệ nào được đặt. Điều này có thể được gọi bởi trình xử lý ngoại lệ tùy chỉnh muốn trì hoãn hành vi xử lý mặc định

tham số bối cảnh có cùng ý nghĩa như trong

. call_exception_handler(bối cảnh)

Gọi trình xử lý ngoại lệ vòng lặp sự kiện hiện tại

bối cảnh là một đối tượng

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

if __name__ == '__main__':
    asyncio.run(main())
58 chứa các khóa sau (các khóa mới có thể được giới thiệu trong các phiên bản Python trong tương lai)

  • 'tin nhắn'. Thông báo lỗi;

  • 'ngoại lệ' (tùy chọn). đối tượng ngoại lệ;

  • 'tương lai' (tùy chọn). ví dụ;

  • ‘task’ (optional). ví dụ;

  • 'xử lý' (tùy chọn). ví dụ;

  • 'giao thức' (tùy chọn). ví dụ;

  • 'vận chuyển' (tùy chọn). ví dụ;

  • 'ổ cắm' (tùy chọn). ví dụ;

  • 'không đồng bộ' (tùy chọn). Máy phát điện không đồng bộ gây ra

    sự ngoại lệ

Ghi chú

Phương thức này không nên bị quá tải trong các vòng lặp sự kiện được phân lớp. Để xử lý ngoại lệ tùy chỉnh, hãy sử dụng phương thức

. get_debug()

Nhận chế độ gỡ lỗi () của vòng lặp sự kiện

Giá trị mặc định là

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7 nếu biến môi trường được đặt thành một chuỗi không trống, nếu không thì là
# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
45

. set_debug(đã bật. )

Đặt chế độ gỡ lỗi của vòng lặp sự kiện

Đã thay đổi trong phiên bản 3. 7. Cái mới hiện cũng có thể được sử dụng để bật chế độ gỡ lỗi.

Xem thêm

Các

Các phương pháp được mô tả trong tiểu mục này ở mức độ thấp. Thay vào đó, trong mã async/await thông thường, hãy cân nhắc sử dụng các chức năng cấp cao và tiện lợi

Ghi chú

Trên Windows, vòng lặp sự kiện mặc định hỗ trợ các quy trình con, trong khi đó thì không. Xem để biết chi tiết

coroutine . sub process_exec(protocol_factory , * . PIPEargs, stdin=subprocess.PIPE , stdout=quy trình con. PIPE , stderr=quy trình con. ỐNG , **kwargs)

Tạo một quy trình con từ một hoặc nhiều đối số chuỗi được chỉ định bởi args

args phải là một danh sách các chuỗi được đại diện bởi

  • ;

  • hoặc , được mã hóa thành

Chuỗi đầu tiên chỉ định chương trình có thể thực thi được và các chuỗi còn lại chỉ định các đối số. Cùng nhau, chuỗi đối số từ ________ 63 ______ 78 của chương trình

Điều này tương tự với lớp thư viện tiêu chuẩn được gọi với

import asyncio
import concurrent.futures

def blocking_io():
    # File operations (such as logging) can block the
    # event loop: run them in a thread pool.
    with open('/dev/urandom', 'rb') as f:
        return f.read(100)

def cpu_bound():
    # CPU-bound operations will block the event loop:
    # in general it is preferable to run them in a
    # process pool.
    return sum(i * i for i in range(10 ** 7))

async def main():
    loop = asyncio.get_running_loop()

    ## Options:

    # 1. Run in the default loop's executor:
    result = await loop.run_in_executor(
        None, blocking_io)
    print('default thread pool', result)

    # 2. Run in a custom thread pool:
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, blocking_io)
        print('custom thread pool', result)

    # 3. Run in a custom process pool:
    with concurrent.futures.ProcessPoolExecutor() as pool:
        result = await loop.run_in_executor(
            pool, cpu_bound)
        print('custom process pool', result)

if __name__ == '__main__':
    asyncio.run(main())
80 và danh sách các chuỗi được truyền làm đối số đầu tiên;

protocol_factory phải có thể gọi được trả về một lớp con của lớp

thông số khác

  • stdin có thể là bất kỳ trong số này

    • một đối tượng giống như tệp đại diện cho một đường ống được kết nối với luồng đầu vào tiêu chuẩn của quy trình con bằng cách sử dụng

    • hằng số (mặc định) sẽ tạo một đường ống mới và kết nối nó,

    • giá trị

      import asyncio
      
      def hello_world(loop):
          """A callback to print 'Hello World' and stop the event loop"""
          print('Hello World')
          loop.stop()
      
      loop = asyncio.new_event_loop()
      
      # Schedule a call to hello_world()
      loop.call_soon(hello_world, loop)
      
      # Blocking call interrupted by loop.stop()
      try:
          loop.run_forever()
      finally:
          loop.close()
      
      3 sẽ làm cho quy trình con kế thừa bộ mô tả tệp từ quy trình này

    • hằng số cho biết tệp đặc biệt sẽ được sử dụng

  • thiết bị xuất chuẩn có thể là bất kỳ trong số này

    • một đối tượng giống như tệp đại diện cho một đường ống được kết nối với luồng đầu ra tiêu chuẩn của quy trình con bằng cách sử dụng

    • hằng số (mặc định) sẽ tạo một đường ống mới và kết nối nó,

    • giá trị

      import asyncio
      
      def hello_world(loop):
          """A callback to print 'Hello World' and stop the event loop"""
          print('Hello World')
          loop.stop()
      
      loop = asyncio.new_event_loop()
      
      # Schedule a call to hello_world()
      loop.call_soon(hello_world, loop)
      
      # Blocking call interrupted by loop.stop()
      try:
          loop.run_forever()
      finally:
          loop.close()
      
      3 sẽ làm cho quy trình con kế thừa bộ mô tả tệp từ quy trình này

    • hằng số cho biết tệp đặc biệt sẽ được sử dụng

  • stderr có thể là bất kỳ trong số này

    • một đối tượng giống như tệp đại diện cho một đường ống được kết nối với luồng lỗi tiêu chuẩn của quy trình con bằng cách sử dụng

    • hằng số (mặc định) sẽ tạo một đường ống mới và kết nối nó,

    • giá trị

      import asyncio
      
      def hello_world(loop):
          """A callback to print 'Hello World' and stop the event loop"""
          print('Hello World')
          loop.stop()
      
      loop = asyncio.new_event_loop()
      
      # Schedule a call to hello_world()
      loop.call_soon(hello_world, loop)
      
      # Blocking call interrupted by loop.stop()
      try:
          loop.run_forever()
      finally:
          loop.close()
      
      3 sẽ làm cho quy trình con kế thừa bộ mô tả tệp từ quy trình này

    • hằng số cho biết tệp đặc biệt sẽ được sử dụng

    • hằng số sẽ kết nối luồng lỗi tiêu chuẩn với luồng đầu ra tiêu chuẩn của quy trình

  • Tất cả các đối số từ khóa khác được chuyển đến mà không cần giải thích, ngoại trừ bufsize, universal_newlines, shell, văn bản, mã hóa và lỗi, hoàn toàn không được chỉ định

    API quy trình con

    async def client_connected(reader, writer):
        # Communicate with the client with
        # reader/writer streams.  For example:
        await reader.readline()
    
    async def main(host, port):
        srv = await asyncio.start_server(
            client_connected, host, port)
        await srv.serve_forever()
    
    asyncio.run(main('127.0.0.1', 0))
    
    9 không hỗ trợ giải mã các luồng dưới dạng văn bản. có thể được sử dụng để chuyển đổi các byte được trả về từ luồng thành văn bản

Xem hàm tạo của lớp để biết tài liệu về các đối số khác

Trả về một cặp

import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.new_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
4, trong đó vận chuyển phù hợp với lớp cơ sở và giao thức là một đối tượng được khởi tạo bởi giao thức_factory

coroutine . sub process_shell(protocol_factory , cmd . PIPE, *, stdin=subprocess.PIPE , stdout=subprocess. PIPE , stderr=quy trình con. ỐNG , **kwargs)

Tạo một quy trình con từ cmd, có thể là một hoặc một chuỗi được mã hóa thành , sử dụng cú pháp “shell” của nền tảng

Điều này tương tự với lớp thư viện tiêu chuẩn được gọi với

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
08

protocol_factory phải có thể gọi được trả về một lớp con của lớp

Xem để biết thêm chi tiết về các đối số còn lại

Trả về một cặp

import asyncio
import datetime

def display_date(end_time, loop):
    print(datetime.datetime.now())
    if (loop.time() + 1.0) < end_time:
        loop.call_later(1, display_date, end_time, loop)
    else:
        loop.stop()

loop = asyncio.new_event_loop()

# Schedule the first call to display_date()
end_time = loop.time() + 5.0
loop.call_soon(display_date, end_time, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
4, trong đó vận chuyển phù hợp với lớp cơ sở và giao thức là một đối tượng được khởi tạo bởi giao thức_factory

Ghi chú

Ứng dụng có trách nhiệm đảm bảo rằng tất cả các khoảng trắng và ký tự đặc biệt được trích dẫn một cách thích hợp để tránh các lỗ hổng. Hàm này có thể được sử dụng để thoát đúng khoảng trắng và các ký tự đặc biệt trong các chuỗi sẽ được sử dụng để xây dựng các lệnh trình bao

Xử lý gọi lại

lớp không đồng bộ. Xử lý

Một đối tượng trình bao gọi lại được trả về bởi,

hủy()

Hủy cuộc gọi lại. Nếu cuộc gọi lại đã bị hủy hoặc được thực thi, phương pháp này không có hiệu lực

đã hủy()

Trả lại

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7 nếu cuộc gọi lại bị hủy

Mới trong phiên bản 3. 7

lớp không đồng bộ. Xử lý hẹn giờ

Một đối tượng trình bao gọi lại được trả về bởi và

Lớp này là lớp con của

khi nào()

Trả lại thời gian gọi lại theo lịch trình dưới dạng giây

Thời gian là dấu thời gian tuyệt đối, sử dụng tham chiếu thời gian giống như

Mới trong phiên bản 3. 7

đối tượng máy chủ

Các đối tượng máy chủ được tạo bởi , , và các hàm

Không khởi tạo lớp trực tiếp

lớp không đồng bộ. Máy chủ

Đối tượng máy chủ là trình quản lý bối cảnh không đồng bộ. Khi được sử dụng trong câu lệnh

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
26, đảm bảo rằng đối tượng Máy chủ đã đóng và không chấp nhận các kết nối mới khi câu lệnh
srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
26 được hoàn thành

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.

Đã thay đổi trong phiên bản 3. 7. Đối tượng máy chủ là trình quản lý bối cảnh không đồng bộ kể từ Python 3. 7.

đóng()

Ngừng phục vụ. đóng ổ cắm nghe và đặt thuộc tính thành

import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()
3

Các ổ cắm đại diện cho các kết nối máy khách đến hiện có được để mở

Máy chủ bị đóng không đồng bộ, hãy sử dụng coroutine để đợi cho đến khi máy chủ được đóng

get_loop()

Trả về vòng lặp sự kiện được liên kết với đối tượng máy chủ

Mới trong phiên bản 3. 7

coroutine start_serving()

Bắt đầu chấp nhận kết nối

Phương thức này là idempotent, vì vậy nó có thể được gọi khi máy chủ đang phục vụ

Tham số chỉ dành cho từ khóa start_serving để và cho phép tạo đối tượng Máy chủ không chấp nhận kết nối ban đầu. Trong trường hợp này là

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
46, hoặc có thể được sử dụng để làm cho Máy chủ bắt đầu chấp nhận kết nối

Mới trong phiên bản 3. 7

coroutine serve_forever()

Bắt đầu chấp nhận kết nối cho đến khi quy trình đăng ký bị hủy. Việc hủy nhiệm vụ

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
35 khiến máy chủ bị đóng

Phương thức này có thể được gọi nếu máy chủ đã chấp nhận kết nối. Chỉ có thể tồn tại một tác vụ

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
35 trên một đối tượng Máy chủ

Example

async def client_connected(reader, writer):
    # Communicate with the client with
    # reader/writer streams.  For example:
    await reader.readline()

async def main(host, port):
    srv = await asyncio.start_server(
        client_connected, host, port)
    await srv.serve_forever()

asyncio.run(main('127.0.0.1', 0))

Mới trong phiên bản 3. 7

is_serving()

Trả lại

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7 nếu máy chủ chấp nhận kết nối mới

Mới trong phiên bản 3. 7

coroutine wait_closed()

Chờ cho đến khi phương pháp hoàn thành

ổ cắm

Danh sách các đối tượng mà máy chủ đang lắng nghe

Đã thay đổi trong phiên bản 3. 7. Trước Python 3. 7

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
40 được sử dụng để trả về trực tiếp danh sách ổ cắm máy chủ nội bộ. Trong 3. 7 một bản sao của danh sách đó được trả về.

Triển khai vòng lặp sự kiện

asyncio vận chuyển với hai triển khai vòng lặp sự kiện khác nhau. Và

Theo mặc định, asyncio được cấu hình để sử dụng trên Unix và trên Windows

lớp không đồng bộ. SelectorEventLoop

Một vòng lặp sự kiện dựa trên mô-đun

Sử dụng bộ chọn hiệu quả nhất có sẵn cho nền tảng nhất định. Cũng có thể định cấu hình thủ công việc triển khai bộ chọn chính xác sẽ được sử dụng

import asyncio
import selectors

class MyPolicy(asyncio.DefaultEventLoopPolicy):
   def new_event_loop(self):
      selector = selectors.SelectSelector()
      return asyncio.SelectorEventLoop(selector)

asyncio.set_event_loop_policy(MyPolicy())

Hệ điều hành Unix, Windows

lớp không đồng bộ. ProactorEventLoop

Vòng lặp sự kiện dành cho Windows sử dụng “Cổng hoàn thành I/O” (IOCP)

các cửa sổ

Xem thêm

Tài liệu MSDN về Cổng hoàn thành I/O

lớp không đồng bộ. Vòng lặp sự kiện trừu tượng

Lớp cơ sở trừu tượng cho các vòng lặp sự kiện tuân thủ không đồng bộ

Phần này liệt kê tất cả các phương pháp mà một triển khai thay thế của

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
46 nên đã xác định

ví dụ

Lưu ý rằng tất cả các ví dụ trong phần này đều có mục đích hiển thị cách sử dụng API vòng lặp sự kiện cấp thấp, chẳng hạn như và. Các ứng dụng asyncio hiện đại hiếm khi cần phải viết theo cách này;

Xin chào thế giới với call_soon()

Một ví dụ sử dụng phương pháp để lên lịch gọi lại. Cuộc gọi lại hiển thị

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
51 và sau đó dừng vòng lặp sự kiện

import asyncio

def hello_world(loop):
    """A callback to print 'Hello World' and stop the event loop"""
    print('Hello World')
    loop.stop()

loop = asyncio.new_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
try:
    loop.run_forever()
finally:
    loop.close()

Xem thêm

Một ví dụ tương tự được tạo bằng coroutine và hàm

Hiển thị ngày hiện tại với call_later()

Một ví dụ về cuộc gọi lại hiển thị ngày hiện tại mỗi giây. Cuộc gọi lại sử dụng phương thức để tự lên lịch lại sau 5 giây và sau đó dừng vòng lặp sự kiện

Tham số sự kiện trong Python là gì?

sự kiện. tham số mà bạn truyền vào khi gọi hàm . Trong Python 2. 7, giá trị của tham số này thuộc loại CHUỖI. In the Python 3 runtime environment, the value of this parameter is in the BYTES type. bối cảnh. the runtime context provided when the FC function is invoked.

What is an example of event in programming?

Sự kiện là các hành động hoặc sự kiện xảy ra trong hệ thống mà bạn đang lập trình, mà hệ thống sẽ cho bạn biết để mã của bạn có thể phản ứng với chúng. Ví dụ: nếu người dùng nhấp vào nút trên trang web, bạn có thể muốn phản ứng lại hành động đó bằng cách hiển thị hộp thông tin .

How does Python handle events?

Introduction to Python Event Handler. Trình xử lý sự kiện là một lớp, một phần của sự kiện, chỉ chịu trách nhiệm quản lý tất cả các lệnh gọi lại sẽ được thực thi khi được gọi . Sự kiện chỉ đơn giản là một hành động, chẳng hạn như nhấp vào nút, sau đó dẫn đến một sự kiện khác mà nhà phát triển đã chỉ định.

What is event in function event?

An Event function is an asynchronous task function that is associated with an Event Listener . An Event function is created to execute a task or a set of tasks on the occurrence of a specified event.