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

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

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

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

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

không đồng bộ. get_running_loop[]

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

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

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

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

không đồng bộ. get_event_loop[]

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

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

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

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

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

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

Ghi chú

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

không đồng bộ. set_event_loop[vòng lặp]

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

không đồng bộ. new_event_loop[]

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

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

Contents

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

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

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

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

  • The section documents the and classes;

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

Event Loop Methods

Event loops have low-level APIs for the following

loop. run_until_complete[future]

Run until the future [an instance of ] has completed

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

Return the Future’s result or raise its exception

loop. run_forever[]

Run the event loop until is called

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

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

loop. stop[]

Stop the event loop

loop. is_running[]

Return

srv = await loop.create_server[...]

async with srv:
    # some code

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

loop. is_closed[]

Trả lại

srv = await loop.create_server[...]

async with srv:
    # some code

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

loop. close[]

Close the event loop

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

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

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

coroutine loop. shutdown_asyncgens[]

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

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

Example

try:
    loop.run_forever[]
finally:
    loop.run_until_complete[loop.shutdown_asyncgens[]]
    loop.close[]

New in version 3. 6

coroutine loop. shutdown_default_executor[]

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

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

async def main[host, port]:
    srv = await asyncio.start_server[
        client_connected, host, port]
    await srv.serve_forever[]

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

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

New in version 3. 9

loop. call_soon[callback , *args , context=None]

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

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

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

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

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

loop. call_soon_threadsafe[callback , *args , context=None]

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

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

See the section of the documentation

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

Ghi chú

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

# will schedule "print["Hello", flush=True]"
loop.call_soon[
    functools.partial[print, "Hello", flush=True]]

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

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

loop. call_later[delay , callback , *args , context=None]

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

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

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

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

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

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

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

loop. call_at[when , callback , *args , context=None]

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

This method’s behavior is the same as

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

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

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

. thời gian[]

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

Ghi chú

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

Xem thêm

Chức năng

. tạo_tương lai[]

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

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

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

loop. create_task[coro , * , name=None , context=None]

Schedule the execution of coro. Return a object

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

If the name argument is provided and not

import asyncio

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

loop = asyncio.new_event_loop[]

# Schedule a call to hello_world[]
loop.call_soon[hello_world, loop]

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

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

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

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

loop. set_task_factory[factory]

Set a task factory that will be used by

If factory is

import asyncio

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

loop = asyncio.new_event_loop[]

# Schedule a call to hello_world[]
loop.call_soon[hello_world, loop]

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

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

loop = asyncio.new_event_loop[]

# Schedule a call to hello_world[]
loop.call_soon[hello_world, loop]

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

loop. get_task_factory[]

Return a task factory or

import asyncio

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

loop = asyncio.new_event_loop[]

# Schedule a call to hello_world[]
loop.call_soon[hello_world, loop]

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

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

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

The socket family can be either or depending on host [or the family argument, if provided]

The socket type will be

protocol_factory must be a callable returning an implementation

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

import asyncio
import datetime

def display_date[end_time, loop]:
    print[datetime.datetime.now[]]
    if [loop.time[] + 1.0] 

Chủ Đề