本文整理汇总了Python中socket.getdefaulttimeout函数的典型用法代码示例。如果您正苦于以下问题:Python getdefaulttimeout函数的具体用法?Python getdefaulttimeout怎么用?Python getdefaulttimeout使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getdefaulttimeout函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: feedsStatus
def feedsStatus(self):
from urllib import urlopen
import socket
self["tl_red"].hide()
self["tl_yellow"].hide()
self["tl_green"].hide()
currentTimeoutDefault = socket.getdefaulttimeout()
socket.setdefaulttimeout(3)
try:
d = urlopen("http://openvix.co.uk/TrafficLightState.php")
self.trafficLight = d.read()
if self.trafficLight == "unstable":
self["tl_off"].hide()
self["tl_red"].show()
elif self.trafficLight == "updating":
self["tl_off"].hide()
self["tl_yellow"].show()
elif self.trafficLight == "stable":
self["tl_off"].hide()
self["tl_green"].show()
else:
self.trafficLight = "unknown"
self["tl_off"].show()
except:
self.trafficLight = "unknown"
self["tl_off"].show()
socket.setdefaulttimeout(currentTimeoutDefault)
示例2: testDefaultTimeout
def testDefaultTimeout(self):
# Testing default timeout
# The default timeout should initially be None
self.assertEqual(socket.getdefaulttimeout(), None)
s = socket.socket()
self.assertEqual(s.gettimeout(), None)
s.close()
# Set the default timeout to 10, and see if it propagates
socket.setdefaulttimeout(10)
self.assertEqual(socket.getdefaulttimeout(), 10)
s = socket.socket()
self.assertEqual(s.gettimeout(), 10)
s.close()
# Reset the default timeout to None, and see if it propagates
socket.setdefaulttimeout(None)
self.assertEqual(socket.getdefaulttimeout(), None)
s = socket.socket()
self.assertEqual(s.gettimeout(), None)
s.close()
# Check that setting it to an invalid value raises ValueError
self.assertRaises(ValueError, socket.setdefaulttimeout, -1)
# Check that setting it to an invalid type raises TypeError
self.assertRaises(TypeError, socket.setdefaulttimeout, "spam")
示例3: __init__
def __init__(self, family_or_realsock=socket.AF_INET, *args, **kwargs):
should_set_nonblocking = kwargs.pop('set_nonblocking', True)
if isinstance(family_or_realsock, (int, long)):
fd = _original_socket(family_or_realsock, *args, **kwargs)
else:
fd = family_or_realsock
# import timeout from other socket, if it was there
try:
self._timeout = fd.gettimeout() or socket.getdefaulttimeout()
except AttributeError:
self._timeout = socket.getdefaulttimeout()
if should_set_nonblocking:
set_nonblocking(fd)
self.fd = fd
# when client calls setblocking(0) or settimeout(0) the socket must
# act non-blocking
self.act_non_blocking = False
# Copy some attributes from underlying real socket.
# This is the easiest way that i found to fix
# https://bitbucket.org/eventlet/eventlet/issue/136
# Only `getsockopt` is required to fix that issue, others
# are just premature optimization to save __getattr__ call.
self.bind = fd.bind
self.close = fd.close
self.fileno = fd.fileno
self.getsockname = fd.getsockname
self.getsockopt = fd.getsockopt
self.listen = fd.listen
self.setsockopt = fd.setsockopt
self.shutdown = fd.shutdown
示例4: get_remote_applications_icon
def get_remote_applications_icon (self):
logging.info ("get remote applications icon")
for n in self.notification:
if not str (n['app_id']) in self.app_ids:
self.app_ids.append (str (n['app_id']))
ids_str = ", ".join (self.app_ids)
qstr = "SELECT icon_url, app_id FROM application WHERE app_id IN (%s)" % ids_str
apps = self._query (qstr)
default_timeout = socket.getdefaulttimeout ()
socket.setdefaulttimeout (GET_ICON_TIMEOUT)
logging.debug ("socket timeout: %s" % socket.getdefaulttimeout ())
timeout_count = 0
for app in apps:
if timeout_count < 3:
try:
icon_name = self.get_remote_icon \
(app['icon_url'], self.app_icons_dir)
except TimeoutError:
logging.debug ("timeout")
timeout_count += 1
icon_name = ""
except NoUpdateError:
logging.debug ("No need update")
icon_name = os.path.basename \
(urlparse.urlsplit (app['icon_url']).path)
else:
icon_name = ""
self.applications[app['app_id']] = {'icon_name': icon_name}
socket.setdefaulttimeout (default_timeout)
self.refresh_status["apps_icon"] = True
示例5: testTimeoutAttribute
def testTimeoutAttribute(self):
# This will prove that the timeout gets through HTTPConnection
# and into the socket.
# default -- use global socket timeout
self.assertIsNone(socket.getdefaulttimeout())
socket.setdefaulttimeout(30)
try:
httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
httpConn.connect()
finally:
socket.setdefaulttimeout(None)
self.assertEqual(httpConn.sock.gettimeout(), 30)
httpConn.close()
# no timeout -- do not use global socket default
self.assertIsNone(socket.getdefaulttimeout())
socket.setdefaulttimeout(30)
try:
httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
timeout=None)
httpConn.connect()
finally:
socket.setdefaulttimeout(None)
self.assertEqual(httpConn.sock.gettimeout(), None)
httpConn.close()
# a value
httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
httpConn.connect()
self.assertEqual(httpConn.sock.gettimeout(), 30)
httpConn.close()
示例6: test_update_feeds_resets_timeout_on_exception
def test_update_feeds_resets_timeout_on_exception(mock_update, hacks_feed):
"""update_feeds resets the socket timeout even on an exception."""
assert socket.getdefaulttimeout() is None
mock_update.side_effect = Exception('Failure')
with pytest.raises(Exception):
update_feeds()
assert socket.getdefaulttimeout() is None
示例7: test_update_feeds
def test_update_feeds(hacks_feed, mocked_parse):
"""update_feeds adds new entries, resets timeout."""
assert socket.getdefaulttimeout() is None
count = update_feeds()
assert count == 2
assert Entry.objects.count() == 2
assert socket.getdefaulttimeout() is None
示例8: get_node
def get_node(cls, external_manager, proxy_class, hostname=None, ssh_port=22, username='root', password=None, isRemote=False, use_keys=False):
key = cls.get_key(proxy_class, hostname, ssh_port, username, password, isRemote, use_keys)
if cls.nodes.get(key) is not None:
return cls.nodes[key]
try:
import time
import datetime
start = datetime.datetime.now()
print 'NODE_PROXY : START ',proxy_class,hostname
print socket.getdefaulttimeout()
print start
node = NodeWrapper(external_manager,proxy_class,hostname,ssh_port,username,password,isRemote,use_keys)
finally:
now = datetime.datetime.now()
print 'NODE_PROXY : END ',hostname,socket.getdefaulttimeout()
print (now - start).seconds
cls._node_pool_lock.acquire()
try:
if cls.nodes.get(key) is None:
cls.nodes[key] = node
print 'Adding to NodePool'
else:
node.cleanup()
return cls.nodes[key]
finally:
cls._node_pool_lock.release()
示例9: fetch
def fetch(self, server):
"""
This function gets your IP from a specific server
"""
t = None
socket_default_timeout = socket.getdefaulttimeout()
opener = urllib.build_opener()
opener.addheaders = [('User-agent',
"Mozilla/5.0 (X11; Linux x86_64; rv:24.0)"
" Gecko/20100101 Firefox/24.0")]
try:
# Close url resource if fetching not finished within timeout.
t = Timer(self.timeout, self.handle_timeout, [self.url])
t.start()
# Open URL.
if version_info[0:2] == (2, 5):
# Support for Python 2.5.* using socket hack
# (Changes global socket timeout.)
socket.setdefaulttimeout(self.timeout)
self.url = opener.open(server)
else:
self.url = opener.open(server, timeout=self.timeout)
# Read response.
content = self.url.read()
# Didn't want to import chardet. Prefered to stick to stdlib
if PY3K:
try:
content = content.decode('UTF-8')
except UnicodeDecodeError:
content = content.decode('ISO-8859-1')
p = '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.('
p += '25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|['
p += '01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
m = re.search(
p,
content)
myip = m.group(0)
if len(myip) > 0:
return myip
else:
return ''
except Exception as e:
print(e)
return ''
finally:
if self.url is not None:
self.url.close()
self.url = None
if t is not None:
t.cancel()
# Reset default socket timeout.
if socket.getdefaulttimeout() != socket_default_timeout:
socket.setdefaulttimeout(socket_default_timeout)
示例10: _socket_create_connection
def _socket_create_connection(address, timeout=None):
if timeout is None:
timeout = socket.getdefaulttimeout()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
oldtimeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(timeout)
sock.connect(address)
socket.setdefaulttimeout(oldtimeout)
return sock
示例11: test_timeout_reset_after_call
def test_timeout_reset_after_call(self):
old_timeout = socket.getdefaulttimeout()
self.stub_urlopen_with_timeout_check(30, None, "url")
try:
socket.setdefaulttimeout(1234)
base_utils.urlopen("url", timeout=30)
self.assertEquals(1234, socket.getdefaulttimeout())
finally:
socket.setdefaulttimeout(old_timeout)
示例12: getTimeout
def getTimeout(self):
"""
Return the timeout set for this session. Should be set in any case,
but just to be sure if..else struct.
"""
if(socket.getdefaulttimeout() != None):
return socket.getdefaulttimeout()
else:
return 'No timeout set'
示例13: testSocketTimeout
def testSocketTimeout(self):
dict = {'logger': self.logger,
'endpoint': 'https://github.com/dmwm',
'cacheduration': None,
'timeout': 10,
}
service = Service(dict)
deftimeout = socket.getdefaulttimeout()
service.getData('%s/socketresettest' % self.testDir, '/WMCore/blob/master/setup.py#L11')
assert deftimeout == socket.getdefaulttimeout()
示例14: testPing
def testPing(self):
import socket
oldTimeOut = socket.getdefaulttimeout()
from angel_app.resource.remote.clone import Clone
cc = Clone("80.219.195.84", 6221)
assert False == cc.ping()
dd = Clone("localhost")
assert True == dd.ping(), "Make sure you have a local provider instance running."
assert oldTimeOut == socket.getdefaulttimeout()
示例15: __init__
def __init__ (self, family = socket.AF_INET, type = socket.SOCK_STREAM, proto = 0, _sock = None,
_hub = None):
"""
Initialize the UV socket
:param family_or_realsock: a socket descriptor or a socket family
"""
self.uv_fd = None
self.uv_handle = None
self.uv_hub = None
self.uv_recv_string = '' # buffer for receiving data...
if isinstance(family, (int, long)):
self.uv_fd = _original_socket(family, type, proto, _sock)
elif isinstance(family, GreenSocket):
_sock = family
self.uv_fd = _sock.uv_fd
if hasattr(_sock, 'uv_hub') and _sock.uv_hub:
_hub = _sock.uv_hub
else:
_sock = family
self.uv_fd = _sock
if not self.uv_hub:
if _hub:
self.uv_hub = _hub
else:
self.uv_hub = weakref.proxy(get_hub())
## check if the socket type is supported by pyUV and we can create a pyUV socket...
if not self.uv_handle:
if self.type == socket.SOCK_STREAM:
self.uv_handle = pyuv.TCP(self.uv_hub.uv_loop)
self.uv_handle.open(self.fileno())
elif self.type == socket.SOCK_DGRAM:
self.uv_handle = pyuv.UDP(self.uv_hub.uv_loop)
self.uv_handle.open(self.fileno())
# import timeout from other socket, if it was there
try:
self._timeout = self.uv_fd.gettimeout() or socket.getdefaulttimeout()
except AttributeError:
self._timeout = socket.getdefaulttimeout()
assert self.uv_fd, 'the socket descriptor must be not null'
set_nonblocking(self.uv_fd)
# when client calls setblocking(0) or settimeout(0) the socket must act non-blocking
self.act_non_blocking = False