Python Tulip ( asyncio) 第3節 Base Event Loop 基本事件循環(3) 譯文

Tulip 的 《基本事件循環》第三篇 (共三篇)

這是很長的一篇 所以分成了幾部分


18.5.1. Base Event Loop  基本事件循環

(...續前文,此爲最後一篇)


8.5.1.8. Low-level socket operations 底層sockert操作

  • BaseEventLoop.sock_recv(socknbytes)

    Receive data from the socket. The return value is a bytes object representing the data received. The maximum amount of data to be received at once is specified by nbytes.

    This method is a coroutine.

    從socket接收數據。返回值是通過byte類型表示接收的數據的對象。每次接收數據的最大值通過nbytes指定。這個方法是一個coroutine


    See also 參見 

    The socket.socket.recv() method. 


  • BaseEventLoop.sock_sendall(sockdata)

    Send data to the socket. The socket must be connected to a remote socket. This method continues to send data from data until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully processed by the receiving end of the connection.

    This method is a coroutine.

    發送數據到sokcet。socket必須連接到一個遠程端口。這個方法不斷從data 發送數據,知道所有數據發送完成或者出現錯誤。成功時返回None 。錯誤時,引發異常,並且無法確定多少數據被成功發送,如果這個方法是一個coroutine


    See also 參見 

    The socket.socket.sendall() method.



  • BaseEventLoop.sock_accept(sock)

    Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address)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.

    接受連接。這個socket必須是顯露一個地址,並且在監聽連接。返回值是一個(conn, address)對,其中的 conn是通過new 操作創建的,用於在這個連接發送和接受數據時的新socket對象,而address 是一個地址,用於暴露端口到其他的連接。


    This method is a coroutine.


    這個方法是一個coroutine


    See also 參見 

    The BaseEventLoop.create_server() method, the start_server() function and the socket.socket.accept() method.

    BaseEventLoop.create_server() 方法,start_server()函數和socket.socket.accept()方法。


18.5.1.9. Resolve host name 解析主機名




18.5.1.10. Connect pipes  連接管道

  • BaseEventLoop.connect_read_pipe(protocol_factorypipe)

    Register read pipe in eventloop. Set the pipe to non-blocking mode.

    protocol_factory should instantiate object with Protocol interface. pipe is a file-like object. Return pair (transport, protocol), where transportsupports the ReadTransport interface.

    This method is a coroutine.

    在事件循環中註冊一個讀取管道。設置pipe爲非阻塞模式。

    protocol_factory應該通過Protocol接口實例化對象。是一個類似文件的對象。返回(transport, protocol)對,其中transport支持ReadTransport接口。

    這個方法是一個coroutine


  • BaseEventLoop.connect_write_pipe(protocol_factorypipe)

    Register write pipe in eventloop.

    protocol_factory should instantiate object with BaseProtocol interface. Pipe is file-like object already switched to nonblocking. Return pair (transport, protocol), where transport support WriteTransport interface.

    This method is a coroutine.

    在事件循環中註冊一個寫管道。

    protocol_factory應該使用BaseProtocol 接口進行實例化。管道是一個類似文件的對象,並且切換到非阻塞模式。返回 (transport, protocol)對,其中transport支持WriteTransport 接口。

   這個方法是一個coroutine

See also 參見 

  The BaseEventLoop.subprocess_exec() and BaseEventLoop.subprocess_shell() methods.

 BaseEventLoop.subprocess_exec()BaseEventLoop.subprocess_shell()方法。 

   

18.5.1.11. UNIX signals UNIX信號

Availability: UNIX only.  僅適用於UNIX系統。

  • BaseEventLoop.add_signal_handler(signumcallback*args)

    Add a handler for a signal.

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

    添加一個信號處理器。

    當信號編號不可用或者無法獲取,產生ValueError 異常。

    當設置處理器出現問題時候,產生RuntimeError 異常。


  • BaseEventLoop.remove_signal_handler(sig)

    Remove a handler for a signal.

    Return True if a signal handler was removed, False if not.

    移除一個信號處理器。

    如果信號處理器被成功移除返回True否者返回False。


See also 參見 

  The signal module.  signal 模塊。


18.5.1.12. Executor 執行器

Call a function in an Executor (pool of threads or pool of processes). By default, an event loop uses a thread pool executor (ThreadPoolExecutor).

調用在執行器(池或進程或進程池中)的函數,默認情況一個事件循環使用一個線程池執行器(ThreadPoolExecutor)。


  • BaseEventLoop.run_in_executor(executorcallback*args)

    Arrange for a callback to be called in the specified executor.

    安排一個回調,調用時在指定的執行器中執行。


    The executor argument should be an Executor instance. The default executor is used if executor is None.

    executor參數一個是一個Executor 實例。默認使用的executorNone


    This method is a coroutine.

    這個方法是一個coroutine




18.5.1.13. Error Handling API  錯誤處理API

Allows to customize how exceptions are handled in the event loop.

允許自定義如何處理事件循環中的異常。


  • BaseEventLoop.set_exception_handler(handler)

    Set handler as the new event loop exception handler.

    handler 設置作爲一個新的事件循環處理器。


    If handler is None, the default exception handler will be set.

    如果handler 爲空,使用默認的異常處理器。


    If handler is a callable object, it should have a matching signature to (loop, context), where loop will be a reference to the active event loop, contextwill be a dict object (see call_exception_handler() documentation for details about context).

    如果handler 是一個回調對象,他需要有一個和 (loop, context)匹配的簽名,其中的loop需要指向一個活動的事件循環,context是一個字典對象(參考call_exception_handler()文檔獲得context的詳情)。


  • BaseEventLoop.default_exception_handler(context)

    Default exception handler.

    默認的異常處理器。

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

    在異常發生時並且沒有設置異常處理器的時候被調用的,並且可以被一個延遲默認處理行爲的自定義異常處理器調用。


    context parameter has the same meaning as in call_exception_handler().

    context參數和call_exception_handler()中的相同。


  • BaseEventLoop.call_exception_handler(context)

    Call the current event loop exception handler.

    調用當前事件循環異常控制器。


    context is a dict object containing the following keys (new keys may be introduced later):

    context 是一個字典對象,包含下面的鍵(新增的鍵稍後介紹):


    Note 注意 

    Note: this method should not be overloaded in subclassed event loops. For any custom exception handling, use set_exception_handler()method

    注意:這個方法不應該被子類的事件循環重載。對於一些自定義異常處理,使用set_exception_handler()方法。



    • ‘message’: Error message;  錯誤消息

    • ‘exception’ (optional): Exception object; 異常對象

    • ‘future’ (optional): asyncio.Future instance; asyncio.Future實例

    • ‘handle’ (optional): asyncio.Handle instance; asynci.Handle實例

    • ‘protocol’ (optional): Protocol instance;  Protocol實例

    • ‘transport’ (optional): Transport instance; Transport實例

    • ‘socket’ (optional): socket.socket instance. socket.socket實例


18.5.1.14. Debug mode  調試模式

  • BaseEventLoop.get_debug()

    Get the debug mode (bool) of the event loop.

    獲得事件循環調試模式。

    The default value is True if the environment variable PYTHONASYNCIODEBUG is set to a non-empty string, False otherwise.

    默認值是True,如果PYTHONASYNCIODEBUG 環境變量設置爲非空值,默認值爲False。

    New in version 3.4.2. 在3.4.2版中新增。


  • BaseEventLoop.set_debug(enabled: bool)

    Set the debug mode of the event loop.

    設置事件循環調試模式。

    New in version 3.4.2. 在3.4.2版中新增。

See also 參見 

The debug mode of asyncio.


18.5.1.15. Server  服務器



    • sockets

      List of socket.socket objects the server is listening to, or None if the server is closed.

      列出socket.socket的正在監聽的對象,如果服務器被關閉,返回None。



    • wait_closed()

      Wait until the close() method completes.

      等待直到close() 方法完成。

      This method is a coroutine.

      此方法爲coroutine


    • close()

      Stop serving: close listening sockets and set the sockets attribute to None.

      The sockets that represent existing incoming client connections are leaved open.

      The server is closed asynchonously, use the wait_closed() coroutine to wait until the server is closed.

      停止服務:管理並監聽端口並設置socket屬性爲None。socket表示已經存在的傳入的保持打開的客戶端連接。使用wait_closed()協程,異步關閉務器。


18.5.1.16. Handle



    • cancel()

      Cancel the call. 取消調用。


18.5.1.17. Event loop examples 事件循環實例

18.5.1.17.1. Hello World with call_soon()

Example using the BaseEventLoop.call_soon() method to schedule a callback. The callback displays "Hello World" and then stops the event loop:

使用BaseEventLoop.call_soon()方法安排一個回調示例,回調顯示“Hello World”並且終止事件循環:

import asyncio

def hello_world(loop):
    print('Hello World')
    loop.stop()
    
loop = asyncio.get_event_loop()

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

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

See also

 

The Hello World coroutine example uses a coroutine.

18.5.1.17.2. Display the current date with call_later()

Example of callback displaying the current date every second. The callback uses the BaseEventLoop.call_later() method to reschedule itself during 5 seconds, and then stops the event loop:

每秒回調顯示當前日期的實例,回調使用BaseEventLoop.call_later()方法,5秒鐘後重新安排自己執行,停止事件循環。

import asyncioimport 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.get_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()
loop.run_forever()
loop.close()

See also

 

The coroutine displaying the current date example uses a coroutine.

18.5.1.17.3. Watch a file descriptor for read events

Wait until a file descriptor received some data using the BaseEventLoop.add_reader() method and then close the event loop:

等待直到接收到文件描述符使用BaseEventLoop.add_reader()接收數據,並關閉事件循環。

import asyncio
try:
    from socket import socketpair
except ImportError:
    from asyncio.windows_utils import socketpair
    
# Create a pair of connected file descriptors
rsock, wsock = socketpair()
loop = asyncio.get_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())

# Run the event loop
loop.run_forever()

# We are done, close sockets and the event loop
rsock.close()
wsock.close()
loop.close()

See also

 

The register an open socket to wait for data using a protocol example uses a low-level protocol created by theBaseEventLoop.create_connection() method.

The register an open socket to wait for data using streams example uses high-level streams created by the open_connection() function in a coroutine.

18.5.1.17.4. Set signal handlers for SIGINT and SIGTERM

Register handlers for signals SIGINT and SIGTERM using the BaseEventLoop.add_signal_handler() method:

使用BaseEventLoop.add_signal_handler()註冊一個SIGINT 和SIGTERM 信號處理器。

import asyncio
import functools
import os
import signal

def ask_exit(signame):
    print("got signal %s: exit" % signame)
    loop.stop()
    
loop = asyncio.get_event_loop()
for signame in ('SIGINT', 'SIGTERM'):
   loop.add_signal_handler(getattr(signal, signame),
       functools.partial(ask_exit, signame))
       
print("Event loop running forever, press CTRL+c to interrupt.")
print("pid %s: send SIGINT or SIGTERM to exit." % os.getpid())

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

This example only works on UNIX.



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章