Python确定HTTPConnection是否无法连接

时间:2014-07-08 15:08:58

标签: python http httpconnection httplib

在Python中,我如何确定HTTPConnection是否无法连接到服务器,例如,服务器地址错误?

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?

2 个答案:

答案 0 :(得分:0)

在实例化对象con.connect()后尝试此操作。

如果无法建立连接,此调用将抛出异常。

示例:

>>> 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

答案 1 :(得分:0)

您可以尝试添加try()except()语句。