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 Show 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
Event Loop MethodsEvent loops have low-level APIs for the following 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 runningloop. 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 đã đóngloop. 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 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 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 objectloop. 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 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
The created transport is an implementation-dependent bidirectional stream Other arguments
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
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. 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
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ố
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. 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 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ố
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. 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 Và 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 Và 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 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. Đă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 Đặ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 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)
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 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
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
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_factorycoroutine . 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ạilớ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ắmDanh 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ệnasyncio 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ộ. SelectorEventLoopMộ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ộ. ProactorEventLoopVò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ượngLớ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. |