Python add command-line arguments and exception handling

Source: Internet
Author: User
Tags socket error


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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.