Chức năng null có phải là python không?

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 các chính sách vòng lặp sự kiện tùy chỉnh được sử dụng), nên sử dụng chức năng này được ưu tiên 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

nội dung

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;

  • Phần này ghi lại các trường hợp và được trả về từ các phương pháp lập lịch trình như và ;

  • 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ư;

  • Phần ghi lại các và các lớp;

  • Phần giới thiệu cách làm việc với một số API vòng lặp sự kiện

Phương thức vòng lặp sự kiện

Các vòng lặp sự kiện có các API cấp thấp cho các mục sau

. run_until_complete(tương lai)

Chạy cho đến khi tương lai (một phiên bản của) hoàn thành

Nếu đối số là a thì nó được lên lịch ngầm định để chạy dưới dạng

Trả lại kết quả của Tương lai hoặc tăng ngoại lệ của nó

. run_forever()

Chạy vòng lặp sự kiện cho đến khi được gọi

Nếu được gọi trước khi được gọi, vòng lặp sẽ thăm dò bộ chọn I/O một lần với thời gian chờ bằng 0, chạy tất cả các lệnh gọi lại đã lên lịch để phản hồi các sự kiện I/O (và những cuộc gọi đã được lên lịch), sau đó thoát

Nếu được gọi trong khi đang chạy, vòng lặp sẽ chạy lô gọi lại hiện tại rồi thoát. Lưu ý rằng các cuộc gọi lại mới được lên lịch bởi các cuộc gọi lại sẽ không chạy trong trường hợp này;

. dừng lại()

Dừng vòng lặp sự kiện

. is_running()

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 hiện đang chạy

. được_đóng()

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

. đóng()

Đóng vòng lặp sự kiện

Vòng lặp không được chạy khi chức năng này được gọi. Mọi cuộc gọi lại đang chờ xử lý sẽ bị loại bỏ

Phương pháp này xóa tất cả các hàng đợi và tắt trình thực thi, nhưng không đợi trình thực thi kết thúc

Phương pháp này là idempotent và không thể đảo ngược. Không có phương thức nào khác được gọi sau khi vòng lặp sự kiện được đóng lại

coroutine . shutdown_asyncgens()

Lên lịch tất cả các đối tượng hiện đang mở để đóng bằng một cuộc gọi. Sau khi gọi phương thức này, vòng lặp sự kiện sẽ đưa ra cảnh báo nếu một trình tạo không đồng bộ mới được lặp lại. Điều này nên được sử dụng để hoàn thiện một cách đáng tin cậy tất cả các trình tạo không đồng bộ theo lịch trình

Lưu ý rằng không cần gọi chức năng này khi được sử dụng

Ví dụ

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

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

coroutine . shutdown_default_executor()

Lên lịch đóng trình thực thi mặc định và đợi nó tham gia tất cả các luồng trong

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. Sau khi gọi phương thức này, a sẽ được nâng lên nếu được gọi trong khi sử dụng trình thực thi mặc định

Lưu ý rằng không cần gọi chức năng này khi được sử dụng

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

. call_soon(gọi lại , *args, context=None)

Lên lịch gọi lại để được gọi với các đối số args ở lần lặp tiếp theo của vòng lặp sự kiện

Các cuộc gọi lại được gọi theo thứ tự mà chúng được đăng ký. Mỗi cuộc gọi lại sẽ được gọi chính xác một lần

Đối số ngữ cảnh chỉ từ khóa tùy chọn cho phép chỉ định một tùy chỉnh để gọi lại chạy trong. Ngữ cảnh hiện tại được sử dụng khi không có ngữ cảnh nào được cung cấp

Một phiên bản của được trả về, có thể được sử dụng sau này để hủy cuộc gọi lại

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

. call_soon_threadsafe(gọi lại , *args, context=None)

Một biến thể thread-safe của. Phải được sử dụng để lên lịch gọi lại từ một luồng khác

Tăng nếu được gọi trên một vòng lặp đã bị đóng. Điều này có thể xảy ra trên luồng phụ khi ứng dụng chính đang tắt

Xem phần tài liệu

Đã thay đổi trong phiên bản 3. 7. Đã thêm thông số ngữ cảnh chỉ từ khóa. Xem PEP 567 để biết thêm chi tiết.

Ghi chú

Hầu hết các chức năng lập lịch trình không cho phép chuyển các đối số từ khóa. Để làm điều đó, sử dụng

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

Sử dụng các đối tượng một phần thường thuận tiện hơn so với sử dụng lambdas, vì asyncio có thể hiển thị các đối tượng một phần tốt hơn trong thông báo lỗi và gỡ lỗi

Vòng lặp sự kiện cung cấp các cơ chế để lên lịch các chức năng gọi lại sẽ được gọi vào một thời điểm nào đó trong tương lai. Vòng lặp sự kiện sử dụng đồng hồ đơn điệu để theo dõi thời gian

. call_later(trễ , gọi lại, *args, context=None)

Lên lịch gọi lại để được gọi sau số giây trì hoãn nhất định (có thể là int hoặc float)

Một phiên bản của được trả về có thể được sử dụng để hủy cuộc gọi lại

gọi lại sẽ được gọi chính xác một lần. Nếu hai cuộc gọi lại được lên lịch chính xác cùng một lúc, thứ tự mà chúng được gọi là không xác định

Các đối số vị trí tùy chọn sẽ được chuyển đến hàm gọi lại khi nó được gọi. Nếu bạn muốn gọi lại với các đối số từ khóa, hãy sử dụng

Đối số ngữ cảnh chỉ từ khóa tùy chọn cho phép chỉ định một tùy chỉnh để gọi lại chạy trong. Ngữ cảnh hiện tại được sử dụng khi không có ngữ cảnh nào được cung cấp

Đã thay đổi trong phiên bản 3. 7. Đã thêm thông số ngữ cảnh chỉ từ khóa. Xem PEP 567 để biết thêm chi tiết.

Đã thay đổi trong phiên bản 3. 8. Trong Python 3. 7 trở về trước với việc triển khai vòng lặp sự kiện mặc định, độ trễ không thể vượt quá một ngày. Điều này đã được sửa trong Python 3. 8.

. call_at(khi , gọi lại, *args, context=None)

Lên lịch gọi lại để được gọi tại dấu thời gian tuyệt đối đã cho khi (một số nguyên hoặc số float), sử dụng cùng tham chiếu thời gian như

Hành vi của phương pháp này giống như

Một phiên bản của được trả về có thể được sử dụng để hủy cuộc gọi lại

Đã thay đổi trong phiên bản 3. 7. Đã thêm thông số ngữ cảnh chỉ từ khóa. Xem PEP 567 để biết thêm chi tiết.

Đã thay đổi trong phiên bản 3. 8. Trong Python 3. 7 trở về trước với việc triển khai vòng lặp sự kiện mặc định, sự khác biệt giữa thời điểm và thời gian hiện tại không thể vượt quá một ngày. Đ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. Điều này cho phép các vòng lặp sự kiện của bên thứ ba cung cấp các triển khai thay thế của đối tượng Tương lai (với hiệu suất hoặc công cụ tốt hơn)

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

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

Lên lịch thực hiện coro. Trả lại một đối tượng

Các vòng lặp sự kiện của bên thứ ba có thể sử dụng lớp con riêng của chúng để có khả năng tương tác. Trong trường hợp này, loại kết quả là một lớp con của

Nếu đối số tên được cung cấp và không phải 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ì nó được đặt làm tên của tác vụ bằng cách sử dụng

Đối số ngữ cảnh chỉ từ khóa tùy chọn cho phép chỉ định tùy chỉnh cho coro chạy trong. Bản sao ngữ cảnh hiện tại được tạo khi không có ngữ cảnh nào được cung cấp

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

Đã thay đổi trong phiên bản 3. 11. Đã thêm tham số ngữ cảnh.

. set_task_factory(nhà máy)

Đặt một nhà máy nhiệm vụ sẽ được sử dụng bởi

Nếu nhà máy 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, nhà máy tác vụ mặc định sẽ được đặt. Mặt khác, nhà máy phải là một hàm có thể gọi được với chữ ký phù hợp vớ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()
8, trong đó vòng lặp là một tham chiếu đến vòng lặp sự kiện đang hoạt động và coro là một đối tượng coroutine. Có thể gọi được phải trả về một đối tượng tương thích

. get_task_factory()

Trả lại nhà máy nhiệm vụ 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 nhà máy mặc định đang được sử dụng

coroutine . 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)

Mở kết nối truyền phát trực tuyến đến một địa chỉ nhất định được chỉ định bởi máy chủ và cổng

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)

Loại ổ cắm sẽ là

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

Phương pháp này sẽ cố gắng thiết lập kết nối trong nền. Khi thành công, nó sẽ 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

Bản tóm tắt theo trình tự thời gian của hoạt động cơ bản như sau

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

  2. protocol_factory được gọi mà không có đối số và dự kiến ​​sẽ trả về một thể hiện

  3. Thể hiện giao thức được kết hợp với phương tiện vận chuyển bằng cách gọi phương thức của nó

  4. Một bộ dữ liệu

    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

Vận chuyển được tạo là một luồng hai chiều phụ thuộc vào việc triển khai

lập luận khác

  • ssl. nếu được cung cấp và không sai, thì truyền tải SSL/TLS được tạo (theo mặc định, truyền tải TCP đơn giản được tạo). Nếu ssl là một đối tượng, bối cảnh này được sử dụng để tạo phương tiện vận chuyển;

    Xem thêm

  • server_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. Chỉ nên được thông qua nếu ssl không phải 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. Theo mặc định, giá trị của đối số máy chủ được sử dụng. Nếu máy chủ trống, không có giá trị mặc định và bạn phải chuyển một giá trị cho server_hostname. Nếu server_hostname là một chuỗi trống, thì tính năng so khớp tên máy chủ bị vô hiệu hóa (đây là một rủi ro bảo mật nghiêm trọng, cho phép xảy ra các cuộc tấn công trung gian tiềm ẩn)

  • family, proto, flags là họ địa chỉ, giao thức và cờ tùy chọn được chuyển qua getaddrinfo() để 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

  • happy_eyeballs_delay, nếu được cung cấp, sẽ bật Happy Eyeballs cho kết nối này. Nó phải là một số dấu phẩy động biểu thị lượng thời gian tính bằng giây để chờ một nỗ lực kết nối hoàn tất, trước khi bắt đầu thử song song tiếp theo. Đây là "Trễ thử kết nối" như được định nghĩa trong RFC 8305. Giá trị mặc định hợp lý do RFC đề xuất là

    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 mili giây)

  • kiểm soát xen kẽ sắp xếp lại địa chỉ khi tên máy chủ phân giải thành nhiều địa chỉ IP. 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 không xác định, thì không có việc sắp xếp lại thứ tự nào được thực hiện và các địa chỉ được thử theo thứ tự được trả về bởi. Nếu một số nguyên dương được chỉ định, các địa chỉ sẽ được xen kẽ theo họ địa chỉ và số nguyên đã cho được hiểu là "Số lượng họ địa chỉ đầu tiên" như được định nghĩa trong RFC 8305. Giá trị mặc định là
    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 nếu happy_eyeballs_delay không được chỉ định và
    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 nếu là

  • sock, nếu được cung cấp, phải là một đối tượng hiện có, đã được kết nối để vận chuyển sử dụng. Nếu sock được cung cấp, không được chỉ định máy chủ, cổng, gia đình, proto, cờ, happy_eyeballs_delay, xen kẽ và local_addr

    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. Để đóng socket, hãy gọi phương thức vận chuyển

  • 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
    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, tương tự như máy chủ và cổng

  • ssl_handshake_timeout là (đối với kết nối 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 là thời gian tính bằng giây để đợi quá trình tắt 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())
    
    3 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)

Đã thay đổi trong phiên bản 3. 5. Đã thêm hỗ trợ cho SSL/TLS trong.

Đã thay đổi trong phiên bản 3. 6. 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. 7. Đã thêm tham số ssl_handshake_timeout.

Đã thay đổi trong phiên bản 3. 8. Đã thêm các tham số happy_eyeballs_delay và xen kẽ.

Thuật toán nhãn cầu hạnh phúc. Thành công với Máy chủ xếp chồng kép. Khi đường dẫn và giao thức IPv4 của máy chủ đang hoạt động, nhưng đường dẫn và giao thức IPv6 của máy chủ không hoạt động, ứng dụng máy khách ngăn xếp kép gặp phải độ trễ kết nối đáng kể so với máy khách chỉ có IPv4. Điều này là không mong muốn vì nó khiến máy khách ngăn xếp kép có trải nghiệm người dùng kém hơn. 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)

Loại ổ cắm sẽ là

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

lập luận khác

  • 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. Để đóng socket, hãy gọi phương thức vận chuyển

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

  • tái sử dụng_địa chỉ yêu cầu hạt nhân sử dụng lại một ổ cắm cục bộ ở trạng thái

    # will schedule "print("Hello", flush=True)"
    loop.call_soon(
        functools.partial(print, "Hello", flush=True))
    
    38 mà không cần đợi hết thời gian chờ tự nhiên của nó. 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 là thời gian tính bằng giây để đợi quá trình tắt 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())
    
    3 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)

  • 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

Đã thay đổi trong phiên bản 3. 5. Đã thêm hỗ trợ cho SSL/TLS trong.

Đã 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. Để đóng socket, hãy gọi phương thức vận chuyển

  • 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 là thời gian tính bằng giây để đợi quá trình tắt 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())
    
    3 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)

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

Đã thay đổi trong phiên bản 3. 7. Đã thêm tham số ssl_handshake_timeout.

Đã 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 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 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. một thể hiện được cấu hình của

  • 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 là (đối với kết nối 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 là thời gian tính bằng giây để đợi quá trình tắt 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())
    
    3 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)

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. Returns

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7 if fd was previously being monitored for writes

See also section for some limitations of these methods

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)

Receive data from sock into the buf buffer. Modeled after the blocking method

Return the number of bytes written to the buffer

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

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

coroutine loop. sock_recvfrom(sock , bufsize)

Receive a datagram of up to bufsize from sock. Asynchronous version of

Return a tuple of (received data, remote address)

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

New in version 3. 11

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

Receive a datagram of up to nbytes from sock into buf. Asynchronous version of

Return a tuple of (number of bytes received, remote address)

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

New in version 3. 11

coroutine loop. sock_sendall(sock , data)

Send data to the sock socket. Asynchronous version of

This method continues to send to the socket until either all data in data has been sent or an error occurs.

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 is returned on success. On error, an exception is raised. Additionally, there is no way to determine how much data, if any, was successfully processed by the receiving end of the connection

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

Changed in version 3. 7. Even though the method was always documented as a coroutine method, before Python 3. 7 it returned a . Since Python 3. 7, this is an

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

coroutine loop. sock_sendto(sock , data , address)

Send a datagram from sock to address. Asynchronous version of

Return the number of bytes sent

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

New in version 3. 11

coroutine loop. sock_connect(sock , address)

Connect sock to a remote socket at address

Asynchronous version of

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

Changed in version 3. 5. 2.

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())
00 no longer needs to be resolved.
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 will try to check if the address is already resolved by calling . If not, will be used to resolve the address.

Xem thêm

and

coroutine loop. sock_accept(sock)

Accept a connection. Modeled after the blocking method

The socket must be bound to an address and listening for connections. The return value is a pair

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 where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection

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

Changed in version 3. 7. Even though the method was always documented as a coroutine method, before Python 3. 7 it returned a . Since Python 3. 7, this is an

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

Xem thêm

and

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

Send a file using high-performance if possible. Return the total number of bytes sent

Asynchronous version of

sock must be a non-blocking

file must be a regular file object open in binary mode

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

fallback, when set to

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
7, makes asyncio manually read and send the file when the platform does not support the sendfile syscall (e. g. Windows or SSL socket on Unix)

Raise if the system does not support sendfile syscall and fallback is

# 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 loop. getaddrinfo(host , port , * , family=0 , type=0 , proto=0 , flags=0)

Asynchronous version of

coroutine loop. getnameinfo(sockaddr , flags=0)

Asynchronous version of

Changed in version 3. 7. Both getaddrinfo and getnameinfo methods were always documented to return a coroutine, but prior to Python 3. 7 they were, in fact, returning objects. Starting with Python 3. 7 both methods are coroutines.

coroutine . connect_read_pipe(protocol_factory , pipe)

Register the read end of pipe in the event loop

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

pipe is a

Return pair

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, where transport supports the interface and protocol is an object instantiated by the protocol_factory

With event loop, the pipe is set to non-blocking mode

coroutine loop. connect_write_pipe(protocol_factory , pipe)

Register the write end of pipe in the event loop

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

pipe is

Return pair

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, where transport supports interface and protocol is an object instantiated by the protocol_factory

With event loop, the pipe is set to non-blocking mode

Ghi chú

does not support the above methods on Windows. Use instead for Windows

Xem thêm

The and methods

loop. add_signal_handler(signum , callback , *args)

Set callback as the handler for the signum signal

The callback will be invoked by loop, along with other queued callbacks and runnable coroutines of that event loop. Unlike signal handlers registered using , a callback registered with this function is allowed to interact with the event loop

Raise if the signal number is invalid or uncatchable. Raise if there is a problem setting up the handler

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

Like , this function must be invoked in the main thread

loop. remove_signal_handler(sig)

Remove the handler for the sig signal

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 signal handler was removed, or
# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
45 if no handler was set for the given signal

Unix

Xem thêm

The module

awaitable loop. run_in_executor(executor , func , *args)

Arrange for func to be called in the specified executor

The executor argument should be an instance. The default executor is used if executor 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

Ví dụ

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())

Note that the entry point guard (

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) is required for option 3 due to the peculiarities of , which is used by . See

This method returns a object

Use to func

Changed in version 3. 5. 3. no longer configures the

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 of the thread pool executor it creates, instead leaving it up to the thread pool executor () to set the default.

loop. set_default_executor(executor)

Set executor as the default executor used by . executor must be an instance of

Changed in version 3. 11. executor must be an instance of .

Allows customizing how exceptions are handled in the event loop

loop. set_exception_handler(handler)

Set handler as the new event loop exception handler

If handler 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 exception handler will be set. Otherwise, handler must be a callable with the signature matching
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, where
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 is a reference to the active event loop, and
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 is 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())
58 object containing the details of the exception (see documentation for details about context)

loop. get_exception_handler()

Return the current exception handler, 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 no custom exception handler was set

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

loop. default_exception_handler(context)

Default exception handler

This is called when an exception occurs and no exception handler is set. This can be called by a custom exception handler that wants to defer to the default handler behavior

context parameter has the same meaning as in

loop. call_exception_handler(context)

Call the current event loop exception handler

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)

  • ‘message’. Error message;

  • ‘exception’ (optional). Exception object;

  • ‘future’ (optional). instance;

  • ‘task’ (optional). instance;

  • '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=quy trình con. 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ý ngữ 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ụ

The start_serving keyword-only parameter to and allows creating a Server object that is not accepting connections initially. In this case

# will schedule "print("Hello", flush=True)"
loop.call_soon(
    functools.partial(print, "Hello", flush=True))
46, or can be used to make the Server start accepting connections

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

coroutine serve_forever()

Start accepting connections until the coroutine is cancelled. Cancellation of

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
35 task causes the server to be closed

This method can be called if the server is already accepting connections. Only one

srv = await loop.create_server(...)

async with srv:
    # some code

# At this point, srv is closed and no longer accepts new connections.
35 task can exist per one Server object

Ví dụ

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()

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 server is accepting new connections

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

coroutine wait_closed()

Wait until the method completes

sockets

List of objects the server is listening on

Changed in version 3. 7. Prior to 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 used to return an internal list of server sockets directly. In 3. 7 a copy of that list is returned.

Event Loop Implementations

asyncio ships with two different event loop implementations. and

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

class asyncio. SelectorEventLoop

An event loop based on the module

Sử dụng bộ chọn hiệu quả nhất có sẵn cho nền tảng nhất định. It is also possible to manually configure the exact selector implementation to be used

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

An event loop for Windows that uses “I/O Completion Ports” (IOCP)

các cửa sổ

Xem thêm

MSDN documentation on I/O Completion Ports

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

Abstract base class for asyncio-compliant event loops

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ụ

Note that all examples in this section purposefully show how to use the low-level event loop APIs, such as and . 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()

An example using the method to schedule a callback. 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