Skip to content
Snippets Groups Projects
Unverified Commit 08aab899 authored by Giuseppe Carboni's avatar Giuseppe Carboni Committed by GitHub
Browse files

Fix #658, implemented a Python class that works as a context manager for sockets (#659)

The Connection class can be used with the python 'with' construct.
parent e02b4af4
No related branches found
No related tags found
No related merge requests found
# Author:
# Giuseppe Carboni, <giuseppe.carboni@inaf.it>
import socket
import time
from contextlib import contextmanager
import ComponentErrorsImpl
class Connection(object):
"""This class implements a contextmanager for a socket.
Usage example:
with Connection(('127.0.0.1', 10000)) as s:
s.sendall('COMMAND\n')
answer = s.recv(1024)
:param: address, a tuple containing IP address and PORT for the socket
:param: timeout, connection timeout, in seconds
"""
def __init__(self, address, timeout=2):
self.address = address
def __enter__(self):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connected = 1
t0 = time.time()
while time.time() - t0 < timeout:
connected = self.s.connect_ex(self.address)
if connected == 0:
break
time.sleep(0.01)
if connected:
reason = 'Could not reach the device!'
from IRAPy import logger
logger.logError(reason)
exc = ComponentErrorsImpl.SocketErrorExImpl()
exc.setData('Reason', reason)
raise exc
return self.s
def __exit__(self, type, value, traceback):
self.s.close()
...@@ -6,10 +6,12 @@ C{from IRAPy import logger} ...@@ -6,10 +6,12 @@ C{from IRAPy import logger}
list of modules: list of modules:
- customlogging: custom logging functionalities to replace standard logging - customlogging: custom logging functionalities to replace standard logging
- bsqueue: BoundedSortedQueue class implements a priority queue structure - bsqueue: BoundedSortedQueue class implements a priority queue structure
- Connection: Connection class implements a contextmanager for a socket
""" """
import customlogging import customlogging
import ACSLog import ACSLog
import Connection
#Some comments required here. The custom logger mechanism is not working in python. #Some comments required here. The custom logger mechanism is not working in python.
#do the way to separate the system logs to the ones do be shown to the user is to use different #do the way to separate the system logs to the ones do be shown to the user is to use different
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment