desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Process items in this queue :param force: Force queue processing (currently not implemented)'
def run(self, force=False):
self.amActive = True with self.lock: if ((self.currentItem is None) or (not self.currentItem.isAlive())): if self.currentItem: self.currentItem.finish() self.currentItem = None if self.queue: def sorter(x, y): u'...
'Implementing classes should call this'
def run(self):
self.inProgress = True
'Implementing Classes should call this'
def finish(self):
self.inProgress = False threading.currentThread().name = self.name
'Remove the Mako cache directory'
@staticmethod def clear_cache():
try: cache_folder = ek(os.path.join, sickbeard.CACHE_DIR, u'mako') if os.path.isdir(cache_folder): shutil.rmtree(cache_folder) except Exception: logger.log(u'Unable to remove the cache/mako directory!', logger.WARNING)
'Print help message for commandline options'
@staticmethod def help_message():
help_msg = __doc__ help_msg = help_msg.replace(u'SickBeard.py', sickbeard.MY_FULLNAME) help_msg = help_msg.replace(u'SickRage directory', sickbeard.PROG_DIR) return help_msg
'Start SickRage'
def start(self):
sickbeard.MY_FULLNAME = ek(os.path.normpath, ek(os.path.abspath, __file__)) sickbeard.MY_NAME = ek(os.path.basename, sickbeard.MY_FULLNAME) sickbeard.PROG_DIR = ek(os.path.dirname, sickbeard.MY_FULLNAME) sickbeard.LOCALE_DIR = ek(os.path.join, sickbeard.PROG_DIR, u'locale') sickbeard.DATA_DIR = sick...
'Fork off as a daemon'
def daemonize(self):
try: pid = os.fork() if (pid != 0): os._exit(0) except OSError as error: sys.stderr.write(u'fork #1 failed: {error_num}: {error_message}\n'.format(error_num=error.errno, error_message=error.strerror)) sys.exit(1) os.setsid() os.umask(0) try: ...
'Remove pid file :param pid_file: to remove :return:'
@staticmethod def remove_pid_file(pid_file):
try: if ek(os.path.exists, pid_file): ek(os.remove, pid_file) except EnvironmentError: return False return True
'Populates the showList with shows from the database'
@staticmethod def load_shows_from_db():
logger.log(u'Loading initial show list', logger.DEBUG) main_db_con = db.DBConnection() sql_results = main_db_con.select(u'SELECT indexer, indexer_id, location FROM tv_shows;') sickbeard.showList = [] for sql_show in sql_results: try: cur_show = TVShow(sql_...
'Restore the Database from a backup :param src_dir: Directory containing backup :param dst_dir: Directory to restore to :return:'
@staticmethod def restore_db(src_dir, dst_dir):
try: files_list = [u'sickbeard.db', u'config.ini', u'failed.db', u'cache.db'] for filename in files_list: src_file = ek(os.path.join, src_dir, filename) dst_file = ek(os.path.join, dst_dir, filename) bak_file = ek(os.path.join, dst_dir, u'{0}.bak-{1}'.format(filen...
'Shut down SickRage :param event: Type of shutdown event, used to see if restart required'
def shutdown(self, event):
if sickbeard.started: sickbeard.halt() sickbeard.saveAll() if self.web_server: logger.log(u'Shutting down Tornado') self.web_server.shutdown() try: self.web_server.join(10) except Exception: pass se...
'Forces SickRage to update to the latest version and exit. :return: True if successful, False otherwise'
@staticmethod def force_update():
def update_with_git(): def run_git(updater, cmd): (stdout_, stderr_, exit_status) = updater._run_git(updater._git_path, cmd) if (not (exit_status == 0)): print(u'Failed to run command: {0} {1}'.format(updater._git_path, cmd)) return Fals...
'bind_addr: address to bind zmq socket on db_name: name of database to write to (created if doesn\'t exist) table_name: name of mongodb \'table\' in the db to write to (created if doesn\'t exist)'
def __init__(self, db_name, table_name, bind_addr='tcp://127.0.0.1:5000'):
self._bind_addr = bind_addr self._db_name = db_name self._table_name = table_name self._conn = pymongo.Connection() self._db = self._conn[self._db_name] self._table = self._db[self._table_name]
'Inserts a document (dictionary) into mongo database table'
def add_document(self, doc):
print ('adding docment %s' % doc) try: self._table.insert(doc) except Exception as e: return ('Error: %s' % e)
'Attempts to return a single document from database table that matches each key/value in keys dictionary.'
def get_document_by_keys(self, keys):
print ('attempting to retrieve document using keys: %s' % keys) try: return self._table.find_one(keys) except Exception as e: return ('Error: %s' % e)
'pack and compress an object with pickle and zlib.'
def send_zipped_pickle(self, obj, flags=0, protocol=(-1)):
pobj = pickle.dumps(obj, protocol) zobj = zlib.compress(pobj) print ('zipped pickle is %i bytes' % len(zobj)) return self.send(zobj, flags=flags)
'reconstruct a Python object sent with zipped_pickle'
def recv_zipped_pickle(self, flags=0):
zobj = self.recv(flags) pobj = zlib.decompress(zobj) return pickle.loads(pobj)
'send a numpy array with metadata'
def send_array(self, A, flags=0, copy=True, track=False):
md = dict(dtype=str(A.dtype), shape=A.shape) self.send_json(md, (flags | zmq.SNDMORE)) return self.send(A, flags, copy=copy, track=track)
'recv a numpy array'
def recv_array(self, flags=0, copy=True, track=False):
md = self.recv_json(flags=flags) msg = self.recv(flags=flags, copy=copy, track=track) A = numpy.frombuffer(msg, dtype=md['dtype']) return A.reshape(md['shape'])
'if heart is beating'
def handle_pong(self, msg):
if (msg[1] == str(self.lifetime)): self.responses.add(msg[0]) else: print ('got bad heartbeat (possibly old?): %s' % msg[1])
'write config to JSON'
def save_config(self, name, cfg):
save_config(name, cfg, self.build_base) save_config(name, cfg, os.path.join('zmq', 'utils')) build_lib_utils = os.path.join(self.build_lib, 'zmq', 'utils') if os.path.exists(build_lib_utils): save_config(name, cfg, build_lib_utils)
'set up compiler settings, based on config'
def init_settings_from_config(self):
cfg = self.config if ((sys.platform == 'win32') and (cfg.get('bundle_msvcp') is None)): if (os.environ.get('PYZMQ_BUNDLE_CRT') or ((sys.version_info >= (3, 5)) and (self.compiler_type == 'msvc') and (not os.environ.get('DISTUTILS_USE_SDK')) and doing_bdist)): cfg['bundle_msvcp'] = True i...
'bundle_libzmq_dylib flag for whether external libzmq library will be included in pyzmq: only relevant when not building libzmq extension'
@property def bundle_libzmq_dylib(self):
if ('bundle_libzmq_dylib' in self.config): return self.config['bundle_libzmq_dylib'] elif ((sys.platform.startswith('win') or self.cross_compiling) and (not self.config['libzmq_extension'])): return True else: return False
'check the zmq version'
def check_zmq_version(self):
cfg = self.config zmq_prefix = cfg['zmq_prefix'] detected = self.test_build(zmq_prefix, self.compiler_settings) vers = tuple(detected['vers']) vs = v_str(vers) if cfg['allow_legacy_libzmq']: min_zmq = min_legacy_zmq else: min_zmq = min_good_zmq if (vers < min_zmq): ...
'Couldn\'t build, fallback after waiting a while'
def fallback_on_bundled(self):
line() warn('\n'.join(["Couldn't find an acceptable libzmq on the system.", '', 'If you expected pyzmq to link against an installed libzmq, please check to make sure:', '', ' * You have a C compiler installed', ' ...
'do a test build ob libzmq'
def test_build(self, prefix, settings):
self.create_tempdir() settings = settings.copy() if (self.bundle_libzmq_dylib and (not sys.platform.startswith('win'))): settings['library_dirs'] = ['zmq'] if (sys.platform == 'darwin'): pass else: settings['runtime_library_dirs'] = [os.path.abspath(pjoin('.',...
'Run the test suite with py.test'
def run(self):
try: import zmq except ImportError: print_exc() fatal('\n '.join(['Could not import zmq!', "You must build pyzmq with 'python setup.py build_ext --inplace' for 'python setup.py test' to work.", 'If you di...
'send, which will only block current greenlet state_changed always fires exactly once (success or fail) at the end of this method.'
def send(self, data, flags=0, copy=True, track=False):
if (flags & zmq.NOBLOCK): try: msg = super(_Socket, self).send(data, flags, copy, track) finally: if (not self.__in_send_multipart): self.__state_changed() return msg flags |= zmq.NOBLOCK while True: try: msg = super(_Socket...
'recv, which will only block current greenlet state_changed always fires exactly once (success or fail) at the end of this method.'
def recv(self, flags=0, copy=True, track=False):
if (flags & zmq.NOBLOCK): try: msg = super(_Socket, self).recv(flags, copy, track) finally: if (not self.__in_recv_multipart): self.__state_changed() return msg flags |= zmq.NOBLOCK while True: try: msg = super(_Socket, self...
'wrap send_multipart to prevent state_changed on each partial send'
def send_multipart(self, *args, **kwargs):
self.__in_send_multipart = True try: msg = super(_Socket, self).send_multipart(*args, **kwargs) finally: self.__in_send_multipart = False self.__state_changed() return msg
'wrap recv_multipart to prevent state_changed on each partial recv'
def recv_multipart(self, *args, **kwargs):
self.__in_recv_multipart = True try: msg = super(_Socket, self).recv_multipart(*args, **kwargs) finally: self.__in_recv_multipart = False self.__state_changed() return msg
'trigger state_changed on getsockopt(EVENTS)'
def get(self, opt):
if (opt in TIMEOS): warnings.warn('TIMEO socket options have no effect in zmq.green', UserWarning) optval = super(_Socket, self).get(opt) if (opt == zmq.EVENTS): self.__state_changed() return optval
'set socket option'
def set(self, opt, val):
if (opt in TIMEOS): warnings.warn('TIMEO socket options have no effect in zmq.green', UserWarning) result = super(_Socket, self).set(opt, val) if (opt in (zmq.SUBSCRIBE, zmq.UNSUBSCRIBE)): self.__state_changed() return result
'Returns three elements tuple with socket descriptors ready for gevent.select.select'
def _get_descriptors(self):
rlist = [] wlist = [] xlist = [] for (socket, flags) in self.sockets: if isinstance(socket, zmq.Socket): rlist.append(socket.getsockopt(zmq.FD)) continue elif isinstance(socket, int): fd = socket elif hasattr(socket, 'fileno'): try:...
'Overridden method to ensure that the green version of Poller is used. Behaves the same as :meth:`zmq.core.Poller.poll`'
def poll(self, timeout=(-1)):
if (timeout is None): timeout = (-1) if (timeout < 0): timeout = (-1) rlist = None wlist = None xlist = None if (timeout > 0): tout = gevent.Timeout.start_new((timeout / 1000.0)) else: tout = None try: (rlist, wlist, xlist) = self._get_descriptors(...
'Enqueue ZMQ address for binding on mon_socket. See zmq.Socket.bind for details.'
def bind_mon(self, addr):
self._mon_binds.append(addr)
'Enqueue ZMQ address for connecting on mon_socket. See zmq.Socket.bind for details.'
def connect_mon(self, addr):
self._mon_connects.append(addr)
'Enqueue setsockopt(opt, value) for mon_socket See zmq.Socket.setsockopt for details.'
def setsockopt_mon(self, opt, value):
self._mon_sockopts.append((opt, value))
'Enqueue ZMQ address for binding on in_socket. See zmq.Socket.bind for details.'
def bind_in(self, addr):
self._in_binds.append(addr)
'Enqueue ZMQ address for connecting on in_socket. See zmq.Socket.connect for details.'
def connect_in(self, addr):
self._in_connects.append(addr)
'Enqueue setsockopt(opt, value) for in_socket See zmq.Socket.setsockopt for details.'
def setsockopt_in(self, opt, value):
self._in_sockopts.append((opt, value))
'Enqueue ZMQ address for binding on out_socket. See zmq.Socket.bind for details.'
def bind_out(self, addr):
self._out_binds.append(addr)
'Enqueue ZMQ address for connecting on out_socket. See zmq.Socket.connect for details.'
def connect_out(self, addr):
self._out_connects.append(addr)
'Enqueue setsockopt(opt, value) for out_socket See zmq.Socket.setsockopt for details.'
def setsockopt_out(self, opt, value):
self._out_sockopts.append((opt, value))
'The runner method. Do not call me directly, instead call ``self.start()``, just like a Thread.'
def run_device(self):
(ins, outs) = self._setup_sockets() device(self.device_type, ins, outs)
'wrap run_device in try/catch ETERM'
def run(self):
try: self.run_device() except ZMQError as e: if (e.errno == ETERM): pass else: raise finally: self.done = True
'Start the device. Override me in subclass for other launchers.'
def start(self):
return self.run()
'wait for me to finish, like Thread.join. Reimplemented appropriately by subclasses.'
def join(self, timeout=None):
tic = time.time() toc = tic while ((not self.done) and (not ((timeout is not None) and ((toc - tic) > timeout)))): time.sleep(0.001) toc = time.time()
'Start the counter'
def start(self):
self._start = self._monotonic()
'Return time since start in microseconds'
def stop(self):
stop = self._monotonic() return int((1000000.0 * (stop - self._start)))
'MessageTracker(*towatch) Create a message tracker to track a set of mesages. Parameters *towatch : tuple of Event, MessageTracker, Message instances. This list of objects to track. This class can track the low-level Events used by the Message class, other MessageTrackers or actual Messages.'
def __init__(self, *towatch):
self.events = set() self.peers = set() for obj in towatch: if isinstance(obj, Event): self.events.add(obj) elif isinstance(obj, MessageTracker): self.peers.add(obj) elif isinstance(obj, Frame): if (not obj.tracker): raise ValueError...
'Is 0MQ completely done with the message(s) being tracked?'
@property def done(self):
for evt in self.events: if (not evt.is_set()): return False for pm in self.peers: if (not pm.done): return False return True
'mt.wait(timeout=-1) Wait for 0MQ to be done with the message or until `timeout`. Parameters timeout : float [default: -1, wait forever] Maximum time in (s) to wait before raising NotDone. Returns None if done before `timeout` Raises NotDone if `timeout` reached before I am done.'
def wait(self, timeout=(-1)):
tic = time.time() if ((timeout is False) or (timeout < 0)): remaining = ((3600 * 24) * 7) else: remaining = timeout done = False for evt in self.events: if (remaining < 0): raise NotDone evt.wait(timeout=remaining) if (not evt.is_set()): ...
'set zmq options by attribute'
def __setattr__(self, key, value):
for obj in ([self] + self.__class__.mro()): if (key in obj.__dict__): object.__setattr__(self, key, value) return upper_key = key.upper() try: opt = getattr(constants, upper_key) except AttributeError: raise AttributeError(('%s has no such opti...
'override if setattr should do something other than call self.set'
def _set_attr_opt(self, name, opt, value):
self.set(opt, value)
'get zmq options by attribute'
def __getattr__(self, key):
upper_key = key.upper() try: opt = getattr(constants, upper_key) except AttributeError: raise AttributeError(('%s has no such option: %s' % (self.__class__.__name__, upper_key))) else: return self._get_attr_opt(upper_key, opt)
'override if getattr should do something other than call self.get'
def _get_attr_opt(self, name, opt):
return self.get(opt)
'p.register(socket, flags=POLLIN|POLLOUT) Register a 0MQ socket or native fd for I/O monitoring. register(s,0) is equivalent to unregister(s). Parameters socket : zmq.Socket or native socket A zmq.Socket or any Python object having a ``fileno()`` method that returns a valid file descriptor. flags : int The events to wa...
def register(self, socket, flags=(POLLIN | POLLOUT)):
if flags: if (socket in self._map): idx = self._map[socket] self.sockets[idx] = (socket, flags) else: idx = len(self.sockets) self.sockets.append((socket, flags)) self._map[socket] = idx elif (socket in self._map): self.unregist...
'Modify the flags for an already registered 0MQ socket or native fd.'
def modify(self, socket, flags=(POLLIN | POLLOUT)):
self.register(socket, flags)
'Remove a 0MQ socket or native fd for I/O monitoring. Parameters socket : Socket The socket instance to stop polling.'
def unregister(self, socket):
idx = self._map.pop(socket) self.sockets.pop(idx) for (socket, flags) in self.sockets[idx:]: self._map[socket] -= 1
'Poll the registered 0MQ or native fds for I/O. Parameters timeout : float, int The timeout in milliseconds. If None, no `timeout` (infinite). This is in milliseconds to be compatible with ``select.poll()``. Returns events : list of tuples The list of events that are ready to be processed. This is a list of tuples of t...
def poll(self, timeout=None):
if ((timeout is None) or (timeout < 0)): timeout = (-1) elif isinstance(timeout, float): timeout = int(timeout) return zmq_poll(self.sockets, timeout=timeout)
'Sockets are context managers .. versionadded:: 14.4'
def __enter__(self):
return self
'Copying a Socket creates a shadow copy'
def __copy__(self, memo=None):
return self.__class__.shadow(self.underlying)
'Shadow an existing libzmq socket address is the integer address of the libzmq socket or an FFI pointer to it. .. versionadded:: 14.1'
@classmethod def shadow(cls, address):
from zmq.utils.interop import cast_int_addr address = cast_int_addr(address) return cls(shadow=address)
'override to allow setting zmq.[UN]SUBSCRIBE even though we have a subscribe method'
def __setattr__(self, key, value):
_key = key.lower() if (_key in ('subscribe', 'unsubscribe')): if isinstance(value, unicode): value = value.encode('utf8') if (_key == 'subscribe'): self.set(zmq.SUBSCRIBE, value) else: self.set(zmq.UNSUBSCRIBE, value) return super(Socket, s...
'Return edge-triggered file descriptor for this socket. This is a read-only edge-triggered file descriptor for both read and write events on this socket. It is important that all available events be consumed when an event is detected, otherwise the read event will not trigger again. .. versionadded:: 17.0'
def fileno(self):
return self.FD
'Subscribe to a topic Only for SUB sockets. .. versionadded:: 15.3'
def subscribe(self, topic):
if isinstance(topic, unicode): topic = topic.encode('utf8') self.set(zmq.SUBSCRIBE, topic)
'Unsubscribe from a topic Only for SUB sockets. .. versionadded:: 15.3'
def unsubscribe(self, topic):
if isinstance(topic, unicode): topic = topic.encode('utf8') self.set(zmq.UNSUBSCRIBE, topic)
'set socket options with a unicode object This is simply a wrapper for setsockopt to protect from encoding ambiguity. See the 0MQ documentation for details on specific options. Parameters option : int The name of the option to set. Can be any of: SUBSCRIBE, UNSUBSCRIBE, IDENTITY optval : unicode string (unicode on py2,...
def set_string(self, option, optval, encoding='utf-8'):
if (not isinstance(optval, unicode)): raise TypeError('unicode strings only') return self.set(option, optval.encode(encoding))
'get the value of a socket option See the 0MQ documentation for details on specific options. Parameters option : int The option to retrieve. Returns optval : unicode string (unicode on py2, str on py3) The value of the option as a unicode string.'
def get_string(self, option, encoding='utf-8'):
if (option not in constants.bytes_sockopts): raise TypeError(('option %i will not return a string to be decoded' % option)) return self.getsockopt(option).decode(encoding)
'bind this socket to a random port in a range If the port range is unspecified, the system will choose the port. Parameters addr : str The address string without the port to pass to ``Socket.bind()``. min_port : int, optional The minimum port in the range of ports to try (inclusive). max_port : int, optional The maximu...
def bind_to_random_port(self, addr, min_port=49152, max_port=65536, max_tries=100):
if (hasattr(constants, 'LAST_ENDPOINT') and (min_port == 49152) and (max_port == 65536)): self.bind(('%s:*' % addr)) url = self.last_endpoint.decode('ascii', 'replace') (_, port_s) = url.rsplit(':', 1) return int(port_s) for i in range(max_tries): try: port = ...
'get the High Water Mark On libzmq ≥ 3, this gets SNDHWM if available, otherwise RCVHWM'
def get_hwm(self):
major = zmq.zmq_version_info()[0] if (major >= 3): try: return self.getsockopt(zmq.SNDHWM) except zmq.ZMQError: pass return self.getsockopt(zmq.RCVHWM) else: return self.getsockopt(zmq.HWM)
'set the High Water Mark On libzmq ≥ 3, this sets both SNDHWM and RCVHWM .. warning:: New values only take effect for subsequent socket bind/connects.'
def set_hwm(self, value):
major = zmq.zmq_version_info()[0] if (major >= 3): raised = None try: self.sndhwm = value except Exception as e: raised = e try: self.rcvhwm = value except Exception as e: raised = e if raised: raise rais...
'send a sequence of buffers as a multipart message The zmq.SNDMORE flag is added to all msg parts before the last. Parameters msg_parts : iterable A sequence of objects to send as a multipart message. Each element can be any sendable object (Frame, bytes, buffer-providers) flags : int, optional SNDMORE is handled autom...
def send_multipart(self, msg_parts, flags=0, copy=True, track=False):
for (i, msg) in enumerate(msg_parts): if isinstance(msg, (zmq.Frame, bytes, _buffer_type)): continue try: _buffer_type(msg) except Exception: rmsg = repr(msg) if (len(rmsg) > 32): rmsg = (rmsg[:32] + '...') raise Typ...
'receive a multipart message as a list of bytes or Frame objects Parameters flags : int, optional Any supported flag: NOBLOCK. If NOBLOCK is set, this method will raise a ZMQError with EAGAIN if a message is not ready. If NOBLOCK is not set, then this method will block until a message arrives. copy : bool, optional Sho...
def recv_multipart(self, flags=0, copy=True, track=False):
parts = [self.recv(flags, copy=copy, track=track)] while self.getsockopt(zmq.RCVMORE): part = self.recv(flags, copy=copy, track=track) parts.append(part) return parts
'Deserialize a received message Override in subclass (e.g. Futures) if recvd is not the raw bytes. The default implementation expects bytes and returns the deserialized message immediately. Parameters load: callable Callable that deserializes bytes recvd: The object returned by self.recv'
def _deserialize(self, recvd, load):
return load(recvd)
'Send a message with a custom serialization function. .. versionadded:: 17 Parameters msg : The message to be sent. Can be any object serializable by `serialize`. serialize : callable The serialization function to use. serialize(msg) should return an iterable of sendable message frames (e.g. bytes objects), which will ...
def send_serialized(self, msg, serialize, flags=0, copy=True):
frames = serialize(msg) return self.send_multipart(frames, flags=flags, copy=copy)
'Receive a message with a custom deserialization function. .. versionadded:: 17 Parameters deserialize : callable The deserialization function to use. deserialize will be called with one argument: the list of frames returned by recv_multipart() and can return any object. flags : int, optional Any valid send flag. copy ...
def recv_serialized(self, deserialize, flags=0, copy=True):
frames = self.recv_multipart(flags=flags, copy=copy) return self._deserialize(frames, deserialize)
'send a Python unicode string as a message with an encoding 0MQ communicates with raw bytes, so you must encode/decode text (unicode on py2, str on py3) around 0MQ. Parameters u : Python unicode string (unicode on py2, str on py3) The unicode string to send. flags : int, optional Any valid send flag. encoding : str [de...
def send_string(self, u, flags=0, copy=True, encoding='utf-8'):
if (not isinstance(u, basestring)): raise TypeError('unicode/str objects only') return self.send(u.encode(encoding), flags=flags, copy=copy)
'receive a unicode string, as sent by send_string Parameters flags : int Any valid recv flag. encoding : str [default: \'utf-8\'] The encoding to be used Returns s : unicode string (unicode on py2, str on py3) The Python unicode string that arrives as encoded bytes.'
def recv_string(self, flags=0, encoding='utf-8'):
msg = self.recv(flags=flags) return self._deserialize(msg, (lambda buf: buf.decode(encoding)))
'send a Python object as a message using pickle to serialize Parameters obj : Python object The Python object to send. flags : int Any valid send flag. protocol : int The pickle protocol number to use. The default is pickle.DEFAULT_PROTOCOL where defined, and pickle.HIGHEST_PROTOCOL elsewhere.'
def send_pyobj(self, obj, flags=0, protocol=DEFAULT_PROTOCOL):
msg = pickle.dumps(obj, protocol) return self.send(msg, flags)
'receive a Python object as a message using pickle to serialize Parameters flags : int Any valid recv flag. Returns obj : Python object The Python object that arrives as a message.'
def recv_pyobj(self, flags=0):
msg = self.recv(flags) return self._deserialize(msg, pickle.loads)
'send a Python object as a message using json to serialize Keyword arguments are passed on to json.dumps Parameters obj : Python object The Python object to send flags : int Any valid send flag'
def send_json(self, obj, flags=0, **kwargs):
from zmq.utils import jsonapi msg = jsonapi.dumps(obj, **kwargs) return self.send(msg, flags)
'receive a Python object as a message using json to serialize Keyword arguments are passed on to json.loads Parameters flags : int Any valid recv flag. Returns obj : Python object The Python object that arrives as a message.'
def recv_json(self, flags=0, **kwargs):
from zmq.utils import jsonapi msg = self.recv(flags) return self._deserialize(msg, (lambda buf: jsonapi.loads(buf, **kwargs)))
'poll the socket for events The default is to poll forever for incoming events. Timeout is in milliseconds, if specified. Parameters timeout : int [default: None] The timeout (in milliseconds) to wait for an event. If unspecified (or specified None), will wait forever for an event. flags : bitfield (int) [default: POL...
def poll(self, timeout=None, flags=POLLIN):
if self.closed: raise ZMQError(ENOTSUP) p = self._poller_class() p.register(self, flags) evts = dict(p.poll(timeout)) return evts.get(self, 0)
'Return a connected PAIR socket ready to receive the event notifications. .. versionadded:: libzmq-4.0 .. versionadded:: 14.0 Parameters events : bitfield (int) [default: ZMQ_EVENTS_ALL] The bitmask defining which events are wanted. addr : string [default: None] The optional endpoint for the monitoring sockets. Return...
def get_monitor_socket(self, events=None, addr=None):
if (zmq.zmq_version_info() < (4,)): raise NotImplementedError(('get_monitor_socket requires libzmq >= 4, have %s' % zmq.zmq_version())) if self._monitor_socket: if self._monitor_socket.closed: self._monitor_socket = None else: return self._monito...
'Shutdown the PAIR socket (created using get_monitor_socket) that is serving socket events. .. versionadded:: 14.4'
def disable_monitor(self):
self._monitor_socket = None self.monitor(None, 0)
'deleting a Context should terminate it, without trying non-threadsafe destroy'
def __del__(self):
if ((not self._shadow) and (not _exiting)): self.term()
'Copying a Context creates a shadow copy'
def __copy__(self, memo=None):
return self.__class__.shadow(self.underlying)
'Shadow an existing libzmq context address is the integer address of the libzmq context or an FFI pointer to it. .. versionadded:: 14.1'
@classmethod def shadow(cls, address):
from zmq.utils.interop import cast_int_addr address = cast_int_addr(address) return cls(shadow=address)
'Shadow an existing pyczmq context ctx is the FFI `zctx_t *` pointer .. versionadded:: 14.1'
@classmethod def shadow_pyczmq(cls, ctx):
from pyczmq import zctx from zmq.utils.interop import cast_int_addr underlying = zctx.underlying(ctx) address = cast_int_addr(underlying) return cls(shadow=address)
'Returns a global Context instance. Most single-threaded applications have a single, global Context. Use this method instead of passing around Context instances throughout your code. A common pattern for classes that depend on Contexts is to use a default argument to enable programs with multiple Contexts but not requi...
@classmethod def instance(cls, io_threads=1):
if ((cls._instance is None) or cls._instance.closed): with cls._instance_lock: if ((cls._instance is None) or cls._instance.closed): cls._instance = cls(io_threads=io_threads) return cls._instance
'Create a Socket associated with this Context. Parameters socket_type : int The socket type, which can be any of the 0MQ socket types: REQ, REP, PUB, SUB, PAIR, DEALER, ROUTER, PULL, PUSH, etc. kwargs: will be passed to the __init__ method of the socket class.'
def socket(self, socket_type, **kwargs):
if self.closed: raise ZMQError(ENOTSUP) s = self._socket_class(self, socket_type, **kwargs) for (opt, value) in self.sockopts.items(): try: s.setsockopt(opt, value) except ZMQError: pass return s
'set default socket options for new sockets created by this Context .. versionadded:: 13.0'
def setsockopt(self, opt, value):
self.sockopts[opt] = value
'get default socket options for new sockets created by this Context .. versionadded:: 13.0'
def getsockopt(self, opt):
return self.sockopts[opt]
'set default sockopts as attributes'
def _set_attr_opt(self, name, opt, value):
if (name in constants.ctx_opt_names): return self.set(opt, value) else: self.sockopts[opt] = value
'get default sockopts as attributes'
def _get_attr_opt(self, name, opt):
if (name in constants.ctx_opt_names): return self.get(opt) elif (opt not in self.sockopts): raise AttributeError(name) else: return self.sockopts[opt]
'delete default sockopts as attributes'
def __delattr__(self, key):
key = key.upper() try: opt = getattr(constants, key) except AttributeError: raise AttributeError(('no such socket option: %s' % key)) else: if (opt not in self.sockopts): raise AttributeError(key) else: del self.sockopts[opt]
'start a timer to fire only once like signal.alarm, but with better resolution than integer seconds.'
@mark.skipif((not hasattr(signal, 'setitimer')), reason='EINTR tests require setitimer') def alarm(self, t=None):
if (t is None): t = self.signal_delay self.timer_fired = False self.orig_handler = signal.signal(signal.SIGALRM, self.stop_timer) signal.setitimer(signal.ITIMER_REAL, t, 1000)
'opening and closing many sockets shouldn\'t cause problems'
def test_many_sockets(self):
ctx = self.Context() for i in range(16): sockets = [ctx.socket(zmq.REP) for i in range(65)] [s.close() for s in sockets] time.sleep(0.01) ctx.term()