处理python套接字中的超时错误

Gre*_*own 27 python sockets error-handling exception

我试图找出如何使用try和除了处理套接字超时.

from socket import *

def main():
    client_socket = socket(AF_INET,SOCK_DGRAM)
    client_socket.settimeout(1)
    server_host = 'localhost'
    server_port = 1234
    while(True):
        client_socket.sendto('Message',(server_host,server_port))
        try:
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.Timeouterror:
            #more code
Run Code Online (Sandbox Code Playgroud)

我添加套接字模块的方法是导入所有内容,但是如何处理文档中的异常,它说你可以使用socket.timeouterror,但这对我不起作用.另外,如果我这样做,我将如何编写try异常块import socket?有人也可以解释进口的差异.

std*_*err 34

from foo import * 
Run Code Online (Sandbox Code Playgroud)

添加所有名称,不带前导下划线(或只有modules __all__属性中定义的名称)foo到当前模块中.

在上面的代码与from socket import *你只是想抓住timeout你已经拉到timeout到当前的命名空间.

from socket import *引入内部所有内容的定义socket但不添加socket自身.

try:
    # socketstuff
except timeout:
    print 'caught a timeout'
Run Code Online (Sandbox Code Playgroud)

许多人认为import *有问题,并试图避免它.这是因为以这种方式导入的2个或更多模块中的公共变量名称将相互破坏.

例如,考虑以下三个python文件:

# a.py
def foo():
    print "this is a's foo function"

# b.py
def foo():
    print "this is b's foo function"

# yourcode.py
from a import *
from b import *
foo()
Run Code Online (Sandbox Code Playgroud)

如果你运行yourcode.py你只会看到输出"这是b的foo函数".

出于这个原因,我建议导入模块并使用它或从模块导入特定名称:

例如,您的代码看起来像显式导入:

import socket
from socket import AF_INET, SOCK_DGRAM

def main():
    client_socket = socket.socket(AF_INET, SOCK_DGRAM)
    client_socket.settimeout(1)
    server_host = 'localhost'
    server_port = 1234
    while(True):
        client_socket.sendto('Message', (server_host, server_port))
        try:
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.timeout:
            #more code
Run Code Online (Sandbox Code Playgroud)

只需要更多的打字,但一切都是明确的,对于读者来说,一切都来自于它.


Tho*_*ner 5

我有足够的成功只是catchig socket.timeoutsocket.error; 虽然可以出于很多原因引发socket.error.小心.

import socket
import logging

hostname='google.com'
port=443

try:
    sock = socket.create_connection((hostname, port), timeout=3)

except socket.timeout as err:
    logging.error(err)

except socket.error as err:
    logging.error(err)
Run Code Online (Sandbox Code Playgroud)