Python network programming-handling socket errors

Source: Internet
Author: User
Tags socket error

In a network application, this is often the case when one party tries to connect, but the other is unable to respond due to network media failure or other reasons.

The Python socket library provides a way to get through the socket. The error gracefully handles socket errors unexpectedly.

1. Code and related explanations

1 #! /usr/bin/env python2 #-*-coding:utf-8-*-3 #Handling Socket Errors4 5 ImportArgparse6 #Python standard module for parsing command-line arguments and options7 ImportSYS8 ImportSocket9 Ten #defining the Main_errors () class One defmain_errors (): A     #creates a parse object, which is described as "Socket Error Examples" -     #Argumentparser (self, prog=none, Usage=none, Description=none, Epilog=none, -     #Version=none, parents=[], Formatter_class=helpformatter, prefix_chars= '-', the     #Fromfile_prefix_chars=none, Argument_default=none, conflict_handler= ' error ', -     #add_help=true) -  -     #Keyword Arguments: +     #-prog-the name of the program (Default:sys.argv[0]) -     #-Usage-A usage message (default:auto-generated from arguments) +     #-Description--A Description of the program does A     #-Epilog--Text following the argument descriptions at     #-Parents--parsers whose arguments should be copied to this one -     #-Formatter_class--helpformatter class for printing help messages -     #-Prefix_chars-characters that prefix optional arguments -     #-Fromfile_prefix_chars-characters that prefix files containing additional arguments -     #-Argument_default-The default value for all arguments -     #-Conflict_handler--String indicating how to handle conflicts in     #-Add_help--Add a-h/-help option -Parser = Argparse. Argumentparser (description='Socket Error Examples') to  +     #using the Add_argument method, add_argument (name or flags ...). [, Action] [, Nargs] [, const] -     #[, default][, type][, choices][, required][, help][, metavar][, dest]) the     #name or flags--the parameter that is required to receive the option parameter or the positional parameter *     #Action: $         #(1) store--default action mode, store value to specified variablePanax Notoginseng         #(2) store_const--storage value is specified in the const portion of the parameter and is used to implement non-Boolean command-line flag -         #(3) store_true/store_false--Boolean switch. can have 2 parameters corresponding to one variable the         #(4) append--store value to list, store value specified in const part of parameter +         #(5) append_const--store value to list, store value specified in const part of parameter A         #(6) version--output version information and then exit the     #nargs--Specifies that multiple or 0 parameters are accepted +     #const--with action= "Store_const|append_const", default value -     #default--setting default values for parameters $     #type--turns the result of input from a named line into a set type, which is often used to check the range of values and legitimacy. Default String $     #choices--checking the range of input parameters -     #required--Specifies that an option appears in the name, false by default, or true to indicate that the parameter must be entered -     #help--Parameter Description the     #metavar--for help information output -     #dest--to associate a position or option with a specific nameWuyi     #http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=21633169&id=4387657 Parameter Explanation theParser.add_argument ('--host', action='Store', dest='Host', required=False) -Parser.add_argument ('--port', action='Store', dest='Port', required=False) WuParser.add_argument ('--file', action='Store', dest='file', required=False) -  About     #Call the Parse_args () method to parse $     #def parse_args (self, Args=none, Namespace=none): -     #args, argv = Self.parse_known_args (args, namespace) -     #if argv: -     #msg = _ (' Unrecognized arguments:%s ') A     #self.error (msg% ". Join (argv)) +     #return args theGiven_args =Parser.parse_args () -Host =Given_args.host $Port =Given_args.port thefilename =Given_args.file the     #First try-except block--Create socket the     #handle creating socket Exceptions the     Try: -s =Socket.socket (socket.af_inet, socket. SOCK_STREAM) in     exceptSocket.error as E: the         Print("Error Creating socket:%s"%e) theSys.exit (1) About     #Second try-except Block--connect to giver Host/port the     #Handling Connection Socket Exceptions the     Try: the S.connect ((host, port)) +     exceptSocket.gaierror as E: -         Print("address-related Error connecting to server:%s"%e) theSys.exit (1)Bayi     #third Try-except block--Sending data the     #Handling Send data errors the     Try: -         #get method sent to Web site -data ="GET%s http/1.0\r\n\r\n"%filename the S.sendall (Data.encode ()) the     exceptSocket.error as E: the         Print("Error sending data:%s"%e) theSys.exit (1) -      while1: the         Try: the             #receive data returned from a Web site theBUF = S.RECV (2048)94         exceptSocket.error as E: the             Print("Error receiving data:%s"%e) the sys.exit () the         if  notLen (buf):98              Break About         #sending BUF data to the command line - sys.stdout.write (str (BUF))101 102 if __name__=='__main__':103Main_errors ()

Python network programming-handling socket errors

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.