Python channel.recv() 方法在无数据可读时会阻塞等待数据退出循环失败解决方法

问题:

while True:
    result0 = channel.recv(1024*1024).decode('utf-8')
    if not result0:  # 如果 result0 为空字符串
        break  # 退出循环
    # 处理 result0 非空的情况
    print(result0)

  退出循环失败

如果这段代码无法退出循环,可能是由于 channel.recv() 方法在无数据可读时会阻塞等待数据,因此需要在退出循环前先关闭 channel 或者设置超时时间。

一种可行的方案是设置 channel.settimeout() 方法,例如:

channel.settimeout(5)  # 设置超时时间为 5 秒

while True:
    try:
        result0 = channel.recv(1024*1024).decode('utf-8')
    except socket.timeout:
        break  # 超时退出循环
    if not result0:
        break
    # 处理 result0 非空的情况
    print(result0)

这里通过 channel.settimeout() 方法将超时时间设置为 5 秒,然后使用 try-except 捕获超时异常,如果捕获到异常则退出循环。

猜你喜欢

转载自blog.csdn.net/songpeiying/article/details/132675559