BlockingIOError 使用 python2 的实现

发布时间: 更新时间: 总字数:173 阅读时间:1m 作者: IP上海 分享 网址

Another Python 2 question! 😊

In Python 2, the equivalent of BlockingIOError is socket.error with an errno attribute set to EAGAIN or EWOULDBLOCK.

Here’s an example:

import socket

try:
    # Perform a blocking I/O operation
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("example.com", 80))
    sock.sendall("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n")
except socket.error, e:
    if e.errno == errno.EAGAIN or e.errno == errno.EWOULDBLOCK:
        print("Blocking I/O error occurred")
    else:
        print("Other socket error occurred:", e)

In this example, we’re trying to perform a blocking I/O operation (connecting to a socket and sending data) and catching the socket.error exception. If the error is due to a blocking I/O operation, we check the errno attribute to see if it’s set to EAGAIN or EWOULDBLOCK, which indicate that the operation would block.

Note that in Python 2, socket.error is a catch-all exception for socket-related errors, and you need to check the errno attribute to determine the specific error.

In Python 3.x, BlockingIOError is a separate exception class that’s raised when a blocking I/O operation is attempted, making it easier to handle these types of errors.

Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数