In Python, how I can determine if HTTPConnection
failed to connect to server, for example, by bad server address?
import httplib
import sys
if len(sys.argv) != 2:
print 'Usage: server'
quit()
con = httplib.HTTPConnection(argv[1]) # how I can determine if this fails?
Try this after instantiating the object con.connect()
.
If the connection is unable to be made, this call will throw an exception.
Example:
>>> import httplib
>>> con = httplib.HTTPConnection('127.0.0.1')
>>> con.connect()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/httplib.py", line 772, in connect
self.timeout, self.source_address)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 111] Connection refused