Exception handling + command-line parsing library Argparse
Socket.error related to General I/O and communication issues
Socket.gaierror related to the query address
Socket.herror related to other address errors
Socket.timeout with a socket settimeout () after the timeout processing about
#-*-coding:utf-8-*-import sysimport socketimport argparse# input parameters via command line python 1_7_socket_errors.py--host= Www.python.org--port=8080--file=1_7_socket_errors.py# can also be directly designated host and port, run. def main (): #创建一个解析器 parser = Argparse. Argumentparser (Description = "Socket Error") #添加参数选项 parser.add_argument ('--host ', action= "store", dest= "host", Requir Ed=false) parser.add_argument ('--port ', action= "store", dest= "Port", Required=false,type=int) parser.add_argument (' --file ', action= "store", dest= "file", Required=false) #调用parse_args () method to parse Given_args = Parser.parse_args () host = Given_args.host port = Given_args.port #也可以自己指定port, host #host = "www.python.org" #port = + filename = giv En_args.file #处理创建套接字异常 try:s = Socket.socket (socket.af_inet,socket. SOCK_STREAM) except Socket.error,e:print "Error creating socket:%s"%e sys.exit (1) #处理连接套接字异常 try: S.connect ((host,port)) except Socket.gaierror,e:print "Address-related ERror connecting to server:%s "%e sys.exit (1) except Socket.error,e:print" Connection error:%s "%e sy S.exit () #处理发送数据错误 try: #GET方法 sent to the Web site S.sendall ("GET%s http/1.0\r\n\r\n"%filename) except SOCKET.E Rror,e:print "Error sending data:%s"%e sys.exit (1) while 1:try: #接受网站给返回的数据 BUF = S.RECV (2048) except Socket.error,e:print "error receiving data:%s"%e sys.exit (1) If not Len (BUF): Break #将buf数据发送到命令行中 Sys.stdout.write (buf) If __name__ = = "__main__": Main ()
Python add command-line arguments and exception handling