desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Set the minimum allowed value (or None for no limit)'
def setMinimum(self, m, update=True):
if (m is not None): m = D(asUnicode(m)) self.opts['bounds'][0] = m if update: self.setValue()
'Return whether or not the spin box is circular.'
def wrapping(self):
return self.opts['wrapping']
'Set whether spin box is circular. Both bounds must be set for this to have an effect.'
def setWrapping(self, s):
self.opts['wrapping'] = s
'Set a string prefix.'
def setPrefix(self, p):
self.setOpts(prefix=p)
'Set the upper and lower limits for values in the spinbox.'
def setRange(self, r0, r1):
self.setOpts(bounds=[r0, r1])
'Set the string suffix appended to the spinbox text.'
def setSuffix(self, suf):
self.setOpts(suffix=suf)
'Set the step size used when responding to the mouse wheel, arrow buttons, or arrow keys.'
def setSingleStep(self, step):
self.setOpts(step=step)
'Set the number of decimals to be displayed when formatting numeric values.'
def setDecimals(self, decimals):
self.setOpts(decimals=decimals)
'Select the numerical portion of the text to allow quick editing by the user.'
def selectNumber(self):
le = self.lineEdit() text = asUnicode(le.text()) m = self.opts['regex'].match(text) if (m is None): return (s, e) = (m.start('number'), m.end('number')) le.setSelection(s, (e - s))
'Return the value of this SpinBox.'
def value(self):
if self.opts['int']: return int(self.val) else: return float(self.val)
'Set the value of this SpinBox. If the value is out of bounds, it will be clipped to the nearest boundary or wrapped if wrapping is enabled. If the spin is integer type, the value will be coerced to int. Returns the actual value set. If value is None, then the current value is used (this is for resetting the value after bounds, etc. have changed)'
def setValue(self, value=None, update=True, delaySignal=False):
if (value is None): value = self.value() bounds = self.opts['bounds'] if ((None not in bounds) and (self.opts['wrapping'] is True)): value = float(value) (l, u) = (float(bounds[0]), float(bounds[1])) value = (((value - l) % (u - l)) + l) else: if ((bounds[0] is not None) and (value < bounds[0])): value = bounds[0] if ((bounds[1] is not None) and (value > bounds[1])): value = bounds[1] if self.opts['int']: value = int(value) if (not isinstance(value, D)): value = D(asUnicode(value)) if (value == self.val): return prev = self.val self.val = value if update: self.updateText(prev=prev) self.sigValueChanging.emit(self, float(self.val)) if (not delaySignal): self.emitChanged() return value
'Return value of text or False if text is invalid.'
def interpret(self):
strn = self.lineEdit().text() try: (val, siprefix, suffix) = fn.siParse(strn, self.opts['regex']) except Exception: return False if ((suffix != self.opts['suffix']) or ((suffix == '') and (siprefix != ''))): return False val = self.opts['evalFunc'](val) if self.opts['int']: val = int(fn.siApply(val, siprefix)) else: try: val = fn.siApply(val, siprefix) except Exception: import sys sys.excepthook(*sys.exc_info()) return False return val
'Edit has finished; set value.'
def editingFinishedEvent(self):
if (asUnicode(self.lineEdit().text()) == self.lastText): return try: val = self.interpret() except Exception: return if (val is False): return if (val == self.val): return self.setValue(val, delaySignal=False)
'Overrides QTreeWidget.setItemWidget such that widgets are added inside an invisible wrapper widget. This makes it possible to move the item in and out of the tree without its widgets being automatically deleted.'
def setItemWidget(self, item, col, wid):
w = QtGui.QWidget() l = QtGui.QVBoxLayout() l.setContentsMargins(0, 0, 0, 0) w.setLayout(l) w.setSizePolicy(wid.sizePolicy()) w.setMinimumHeight(wid.minimumHeight()) w.setMinimumWidth(wid.minimumWidth()) l.addWidget(wid) w.realChild = wid self.placeholders.append(w) QtGui.QTreeWidget.setItemWidget(self, item, col, w)
'Called when item has been dropped elsewhere in the tree. Return True to accept the move, False to reject.'
def itemMoving(self, item, parent, index):
return True
'**Arguments:** suffix (str or None) The suffix to place after the value siPrefix (bool) Whether to add an SI prefix to the units and display a scaled value averageTime (float) The length of time in seconds to average values. If this value is 0, then no averaging is performed. As this value increases the display value will appear to change more slowly and smoothly. formatStr (str) Optionally, provide a format string to use when displaying text. The text will be generated by calling formatStr.format(value=, avgValue=, suffix=) (see Python documentation on str.format) This option is not compatible with siPrefix'
def __init__(self, parent=None, suffix='', siPrefix=False, averageTime=0, formatStr=None):
QtGui.QLabel.__init__(self, parent) self.values = [] self.averageTime = averageTime self.suffix = suffix self.siPrefix = siPrefix if (formatStr is None): formatStr = '{avgValue:0.2g} {suffix}' self.formatStr = formatStr
'data should be a dictionary.'
def setData(self, data, hideRoot=False):
self.clear() self.buildTree(data, self.invisibleRootItem(), hideRoot=hideRoot) self.expandToDepth(3) self.resizeColumnToContents(0)
'Return a list of strings describing the currently enabled filters.'
def describe(self):
desc = [] for fp in self: if (fp.value() is False): continue desc.append(fp.describe()) return desc
'The keyword arguments \'useOpenGL\' and \'backgound\', if specified, are passed to the remote GraphicsView.__init__(). All other keyword arguments are passed to multiprocess.QtProcess.__init__().'
def __init__(self, parent=None, *args, **kwds):
self._img = None self._imgReq = None self._sizeHint = (640, 480) QtGui.QWidget.__init__(self) remoteKwds = {} for kwd in ['useOpenGL', 'background']: if (kwd in kwds): remoteKwds[kwd] = kwds.pop(kwd) self._proc = mp.QtProcess(**kwds) self.pg = self._proc._import('pyqtgraph') self.pg.setConfigOptions(**CONFIG_OPTIONS) rpgRemote = self._proc._import('pyqtgraph.widgets.RemoteGraphicsView') self._view = rpgRemote.Renderer(*args, **remoteKwds) self._view._setProxyOptions(deferGetattr=True) self.setFocusPolicy(QtCore.Qt.StrongFocus) self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.setMouseTracking(True) self.shm = None shmFileName = self._view.shmFileName() if sys.platform.startswith('win'): self.shmtag = shmFileName else: self.shmFile = open(shmFileName, 'r') self._view.sceneRendered.connect(mp.proxy(self.remoteSceneChanged)) for method in ['scene', 'setCentralItem']: setattr(self, method, getattr(self._view, method))
'Return the remote process handle. (see multiprocess.remoteproxy.RemoteEventHandler)'
def remoteProcess(self):
return self._proc
'Close the remote process. After this call, the widget will no longer be updated.'
def close(self):
self._proc.close()
'Set the list of fields to be used by the mapper. The format of *fields* is:: [ (fieldName, {options}), ... ] Field Options: mode Either \'range\' or \'enum\' (default is range). For \'range\', The user may specify a gradient of colors to be applied linearly across a specific range of values. For \'enum\', the user specifies a single color for each unique value (see *values* option). units String indicating the units of the data for this field. values List of unique values for which the user may assign a color when mode==\'enum\'. Optionally may specify a dict instead {value: name}.'
def setFields(self, fields):
self.fields = OrderedDict(fields) names = self.fieldNames() self.setAddList(names)
'Return an array of colors corresponding to *data*. **Arguments:** data A numpy record array where the fields in data.dtype match those defined by a prior call to setFields(). mode Either \'byte\' or \'float\'. For \'byte\', the method returns an array of dtype ubyte with values scaled 0-255. For \'float\', colors are returned as 0.0-1.0 float values.'
def map(self, data, mode='byte'):
if isinstance(data, dict): data = np.array([tuple(data.values())], dtype=[(k, float) for k in data.keys()]) colors = np.zeros((len(data), 4)) for item in self.children(): if (not item['Enabled']): continue chans = item.param('Channels..') mask = np.empty((len(data), 4), dtype=bool) for (i, f) in enumerate(['Red', 'Green', 'Blue', 'Alpha']): mask[:, i] = chans[f] colors2 = item.map(data) op = item['Operation'] if (op == 'Add'): colors[mask] = (colors[mask] + colors2[mask]) elif (op == 'Multiply'): colors[mask] *= colors2[mask] elif (op == 'Overlay'): a = colors2[:, 3:4] c3 = ((colors * (1 - a)) + (colors2 * a)) c3[:, 3:4] = (colors[:, 3:4] + ((1 - colors[:, 3:4]) * a)) colors = c3 elif (op == 'Set'): colors[mask] = colors2[mask] colors = np.clip(colors, 0, 1) if (mode == 'byte'): colors = (colors * 255).astype(np.ubyte) return colors
'Set the selected item to the first one having the given value.'
def setValue(self, value):
text = None for (k, v) in self._items.items(): if (v == value): text = k break if (text is None): raise ValueError(value) self.setText(text)
'Set the selected item to the first one having the given text.'
def setText(self, text):
ind = self.findText(text) if (ind == (-1)): raise ValueError(text) self.setCurrentIndex(ind)
'If items were given as a list of strings, then return the currently selected text. If items were given as a dict, then return the value corresponding to the currently selected key. If the combo list is empty, return None.'
def value(self):
if (self.count() == 0): return None text = asUnicode(self.currentText()) return self._items[text]
'*items* may be a list or a dict. If a dict is given, then the keys are used to populate the combo box and the values will be used for both value() and setValue().'
@ignoreIndexChange @blockIfUnchanged def setItems(self, items):
prevVal = self.value() self.blockSignals(True) try: self.clear() self.addItems(items) finally: self.blockSignals(False) if (self.value() != prevVal): self.currentIndexChanged.emit(self.currentIndex())
'When initializing PlotWidget, *parent* and *background* are passed to :func:`GraphicsWidget.__init__() <pyqtgraph.GraphicsWidget.__init__>` and all others are passed to :func:`PlotItem.__init__() <pyqtgraph.PlotItem.__init__>`.'
def __init__(self, parent=None, background='default', **kargs):
GraphicsView.__init__(self, parent, background=background) self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) self.enableMouse(False) self.plotItem = PlotItem(**kargs) self.setCentralItem(self.plotItem) for m in ['addItem', 'removeItem', 'autoRange', 'clear', 'setXRange', 'setYRange', 'setRange', 'setAspectLocked', 'setMouseEnabled', 'setXLink', 'setYLink', 'enableAutoRange', 'disableAutoRange', 'setLimits', 'register', 'unregister', 'viewRect']: setattr(self, m, getattr(self.plotItem, m)) self.plotItem.sigRangeChanged.connect(self.viewRangeChanged)
'Return the PlotItem contained within.'
def getPlotItem(self):
return self.plotItem
'Initialization arguments: signal - a bound Signal or pyqtSignal instance delay - Time (in seconds) to wait for signals to stop before emitting (default 0.3s) slot - Optional function to connect sigDelayed to. rateLimit - (signals/sec) if greater than 0, this allows signals to stream out at a steady rate while they are being received.'
def __init__(self, signal, delay=0.3, rateLimit=0, slot=None):
QtCore.QObject.__init__(self) signal.connect(self.signalReceived) self.signal = signal self.delay = delay self.rateLimit = rateLimit self.args = None self.timer = ThreadsafeTimer.ThreadsafeTimer() self.timer.timeout.connect(self.flush) self.block = False self.slot = weakref.ref(slot) self.lastFlushTime = None if (slot is not None): self.sigDelayed.connect(slot)
'Received signal. Cancel previous timer and store args to be forwarded later.'
def signalReceived(self, *args):
if self.block: return self.args = args if (self.rateLimit == 0): self.timer.stop() self.timer.start(((self.delay * 1000) + 1)) else: now = time() if (self.lastFlushTime is None): leakTime = 0 else: lastFlush = self.lastFlushTime leakTime = max(0, ((lastFlush + (1.0 / self.rateLimit)) - now)) self.timer.stop() self.timer.start(((min(leakTime, self.delay) * 1000) + 1))
'If there is a signal queued up, send it now.'
def flush(self):
if ((self.args is None) or self.block): return False self.sigDelayed.emit(self.args) self.args = None self.timer.stop() self.lastFlushTime = time() return True
'**Arguments:** maxSize (int) This is the maximum size of the cache. When some item is added and the cache would become bigger than this, it\'s resized to the value passed on resizeTo. resizeTo (int) When a resize operation happens, this is the size of the final cache.'
def __init__(self, maxSize=100, resizeTo=70):
assert (resizeTo < maxSize) self.maxSize = maxSize self.resizeTo = resizeTo self._counter = 0 self._dict = {} if _IS_PY3: self._nextTime = itertools.count(0).__next__ else: self._nextTime = itertools.count(0).next
'An item should call this method if it can handle the event. This will prevent the event being delivered to any other items.'
def accept(self):
self.accepted = True self.acceptedItem = self.currentItem
'An item should call this method if it cannot handle the event. This will allow the event to be delivered to other items.'
def ignore(self):
self.accepted = False
'Return the current scene position of the mouse.'
def scenePos(self):
return Point(self._scenePos)
'Return the current screen position (pixels relative to widget) of the mouse.'
def screenPos(self):
return Point(self._screenPos)
'Return the scene position of the mouse at the time *btn* was pressed. If *btn* is omitted, then the button that initiated the drag is assumed.'
def buttonDownScenePos(self, btn=None):
if (btn is None): btn = self.button() return Point(self._buttonDownScenePos[int(btn)])
'Return the screen position (pixels relative to widget) of the mouse at the time *btn* was pressed. If *btn* is omitted, then the button that initiated the drag is assumed.'
def buttonDownScreenPos(self, btn=None):
if (btn is None): btn = self.button() return Point(self._buttonDownScreenPos[int(btn)])
'Return the scene position of the mouse immediately prior to this event.'
def lastScenePos(self):
return Point(self._lastScenePos)
'Return the screen position of the mouse immediately prior to this event.'
def lastScreenPos(self):
return Point(self._lastScreenPos)
'Return the buttons currently pressed on the mouse. (see QGraphicsSceneMouseEvent::buttons in the Qt documentation)'
def buttons(self):
return self._buttons
'Return the button that initiated the drag (may be different from the buttons currently pressed) (see QGraphicsSceneMouseEvent::button in the Qt documentation)'
def button(self):
return self._button
'Return the current position of the mouse in the coordinate system of the item that the event was delivered to.'
def pos(self):
return Point(self.currentItem.mapFromScene(self._scenePos))
'Return the previous position of the mouse in the coordinate system of the item that the event was delivered to.'
def lastPos(self):
return Point(self.currentItem.mapFromScene(self._lastScenePos))
'Return the position of the mouse at the time the drag was initiated in the coordinate system of the item that the event was delivered to.'
def buttonDownPos(self, btn=None):
if (btn is None): btn = self.button() return Point(self.currentItem.mapFromScene(self._buttonDownScenePos[int(btn)]))
'Returns True if this event is the first since a drag was initiated.'
def isStart(self):
return self.start
'Returns False if this is the last event in a drag. Note that this event will have the same position as the previous one.'
def isFinish(self):
return self.finish
'Return any keyboard modifiers currently pressed. (see QGraphicsSceneMouseEvent::modifiers in the Qt documentation)'
def modifiers(self):
return self._modifiers
'An item should call this method if it can handle the event. This will prevent the event being delivered to any other items.'
def accept(self):
self.accepted = True self.acceptedItem = self.currentItem
'An item should call this method if it cannot handle the event. This will allow the event to be delivered to other items.'
def ignore(self):
self.accepted = False
'Return the current scene position of the mouse.'
def scenePos(self):
return Point(self._scenePos)
'Return the current screen position (pixels relative to widget) of the mouse.'
def screenPos(self):
return Point(self._screenPos)
'Return the buttons currently pressed on the mouse. (see QGraphicsSceneMouseEvent::buttons in the Qt documentation)'
def buttons(self):
return self._buttons
'Return the mouse button that generated the click event. (see QGraphicsSceneMouseEvent::button in the Qt documentation)'
def button(self):
return self._button
'Return True if this is a double-click.'
def double(self):
return self._double
'Return the current position of the mouse in the coordinate system of the item that the event was delivered to.'
def pos(self):
return Point(self.currentItem.mapFromScene(self._scenePos))
'Return the previous position of the mouse in the coordinate system of the item that the event was delivered to.'
def lastPos(self):
return Point(self.currentItem.mapFromScene(self._lastScenePos))
'Return any keyboard modifiers currently pressed. (see QGraphicsSceneMouseEvent::modifiers in the Qt documentation)'
def modifiers(self):
return self._modifiers
'Returns True if the mouse has just entered the item\'s shape'
def isEnter(self):
return self.enter
'Returns True if the mouse has just exited the item\'s shape'
def isExit(self):
return self.exit
'Inform the scene that the item (that the event was delivered to) would accept a mouse click event if the user were to click before moving the mouse again. Returns True if the request is successful, otherwise returns False (indicating that some other item would receive an incoming click).'
def acceptClicks(self, button):
if (not self.acceptable): return False if (button not in self.__clickItems): self.__clickItems[button] = self.currentItem return True return False
'Inform the scene that the item (that the event was delivered to) would accept a mouse drag event if the user were to drag before the next hover event. Returns True if the request is successful, otherwise returns False (indicating that some other item would receive an incoming drag event).'
def acceptDrags(self, button):
if (not self.acceptable): return False if (button not in self.__dragItems): self.__dragItems[button] = self.currentItem return True return False
'Return the current scene position of the mouse.'
def scenePos(self):
return Point(self._scenePos)
'Return the current screen position of the mouse.'
def screenPos(self):
return Point(self._screenPos)
'Return the previous scene position of the mouse.'
def lastScenePos(self):
return Point(self._lastScenePos)
'Return the previous screen position of the mouse.'
def lastScreenPos(self):
return Point(self._lastScreenPos)
'Return the buttons currently pressed on the mouse. (see QGraphicsSceneMouseEvent::buttons in the Qt documentation)'
def buttons(self):
return self._buttons
'Return the current position of the mouse in the coordinate system of the item that the event was delivered to.'
def pos(self):
return Point(self.currentItem.mapFromScene(self._scenePos))
'Return the previous position of the mouse in the coordinate system of the item that the event was delivered to.'
def lastPos(self):
return Point(self.currentItem.mapFromScene(self._lastScenePos))
'Return any keyboard modifiers currently pressed. (see QGraphicsSceneMouseEvent::modifiers in the Qt documentation)'
def modifiers(self):
return self._modifiers
'Workaround for PyQt bug in qgraphicsscene.items() All subclasses of QGraphicsObject must register themselves with this function. (otherwise, mouse interaction with those objects will likely fail)'
@classmethod def registerObject(cls, obj):
if (HAVE_SIP and isinstance(obj, sip.wrapper)): cls._addressCache[sip.unwrapinstance(sip.cast(obj, QtGui.QGraphicsItem))] = obj
'Called before every render. This method will inform items that the scene is about to be rendered by emitting sigPrepareForPaint. This allows items to delay expensive processing until they know a paint will be required.'
def prepareForPaint(self):
self.sigPrepareForPaint.emit()
'Set the distance away from mouse clicks to search for interacting items. When clicking, the scene searches first for items that directly intersect the click position followed by any other items that are within a rectangle that extends r pixels away from the click position.'
def setClickRadius(self, r):
self._clickRadius = r
'Set the distance the mouse must move after a press before mouseMoveEvents will be delivered. This ensures that clicks with a small amount of movement are recognized as clicks instead of drags.'
def setMoveDistance(self, d):
self._moveDistance = d
'Return an iterator that iterates first through the items that directly intersect point (in Z order) followed by any other items that are within the scene\'s click radius.'
def itemsNearEvent(self, event, selMode=QtCore.Qt.IntersectsItemShape, sortOrder=QtCore.Qt.DescendingOrder, hoverable=False):
view = self.views()[0] tr = view.viewportTransform() r = self._clickRadius rect = view.mapToScene(QtCore.QRect(0, 0, (2 * r), (2 * r))).boundingRect() seen = set() if hasattr(event, 'buttonDownScenePos'): point = event.buttonDownScenePos() else: point = event.scenePos() w = rect.width() h = rect.height() rgn = QtCore.QRectF((point.x() - w), (point.y() - h), (2 * w), (2 * h)) items = self.items(point, selMode, sortOrder, tr) items2 = [] for item in items: if (hoverable and (not hasattr(item, 'hoverEvent'))): continue shape = item.shape() if (shape is None): continue if shape.contains(item.mapFromScene(point)): items2.append(item) def absZValue(item): if (item is None): return 0 return (item.zValue() + absZValue(item.parentItem())) sortList(items2, (lambda a, b: cmp(absZValue(b), absZValue(a)))) return items2
'Can be called by any item in the scene to expand its context menu to include parent context menus. Parents may implement getContextMenus to add new menus / actions to the existing menu. getContextMenus must accept 1 argument (the event that generated the original menu) and return a single QMenu or a list of QMenus. The final menu will look like: | Original Item 1 | Original Item 2 | Original Item N | Parent Item 1 | Parent Item 2 | Grandparent Item 1 **Arguments:** item The item that initially created the context menu (This is probably the item making the call to this function) menu The context menu being shown by the item event The original event that triggered the menu to appear.'
def addParentContextMenus(self, item, menu, event):
menusToAdd = [] while (item is not self): item = item.parentItem() if (item is None): item = self if (not hasattr(item, 'getContextMenus')): continue subMenus = (item.getContextMenus(event) or []) if isinstance(subMenus, list): menusToAdd.extend(subMenus) else: menusToAdd.append(subMenus) if menusToAdd: menu.addSeparator() for m in menusToAdd: if isinstance(m, QtGui.QMenu): menu.addMenu(m) elif isinstance(m, QtGui.QAction): menu.addAction(m) else: raise Exception(('Cannot add object %s (type=%s) to QMenu.' % (str(m), str(type(m))))) return menu
'Print a list of all watched objects and whether they have been collected.'
def check(self):
gc.collect() dead = self.allNames[:] alive = [] for k in self.objs: dead.remove(k) alive.append(k) print('Deleted objects:', dead) print('Live objects:', alive)
'Optionally create a new profiler based on caller\'s qualname.'
def __new__(cls, msg=None, disabled='env', delayed=True):
if ((disabled is True) or ((disabled == 'env') and (len(cls._profilers) == 0))): return cls._disabledProfiler caller_frame = sys._getframe(1) try: caller_object_type = type(caller_frame.f_locals['self']) except KeyError: qualifier = caller_frame.f_globals['__name__'].split('.', 1)[1] else: qualifier = caller_object_type.__name__ func_qualname = ((qualifier + '.') + caller_frame.f_code.co_name) if ((disabled == 'env') and (func_qualname not in cls._profilers)): return cls._disabledProfiler cls._depth += 1 obj = super(Profiler, cls).__new__(cls) obj._name = (msg or func_qualname) obj._delayed = delayed obj._markCount = 0 obj._finished = False obj._firstTime = obj._lastTime = ptime.time() obj._newMsg(('> Entering ' + obj._name)) return obj
'Register or print a new message with timing information.'
def __call__(self, msg=None):
if self.disable: return if (msg is None): msg = str(self._markCount) self._markCount += 1 newTime = ptime.time() self._newMsg(' %s: %0.4f ms', msg, ((newTime - self._lastTime) * 1000)) self._lastTime = newTime
'Add a final message; flush the message list if no parent profiler.'
def finish(self, msg=None):
if (self._finished or self.disable): return self._finished = True if (msg is not None): self(msg) self._newMsg('< Exiting %s, total time: %0.4f ms', self._name, ((ptime.time() - self._firstTime) * 1000)) type(self)._depth -= 1 if (self._depth < 1): self.flush()
'Return all objects matching regex that were considered \'new\' when the last diff() was run.'
def findNew(self, regex):
return self.findTypes(self.newRefs, regex)
'Return all objects matching regex that were considered \'persistent\' when the last diff() was run.'
def findPersistent(self, regex):
return self.findTypes(self.persistentRefs, regex)
'Remember the current set of objects as the comparison for all future calls to diff() Called automatically on init, but can be called manually as well.'
def start(self):
(refs, count, objs) = self.collect() for r in self.startRefs: self.forgetRef(self.startRefs[r]) self.startRefs.clear() self.startRefs.update(refs) for r in refs: self.rememberRef(r) self.startCount.clear() self.startCount.update(count)
'Compute all differences between the current object set and the reference set. Print a set of reports for created, deleted, and persistent objects'
def diff(self, **kargs):
(refs, count, objs) = self.collect() delRefs = {} for i in list(self.startRefs.keys()): if (i not in refs): delRefs[i] = self.startRefs[i] del self.startRefs[i] self.forgetRef(delRefs[i]) for i in list(self.newRefs.keys()): if (i not in refs): delRefs[i] = self.newRefs[i] del self.newRefs[i] self.forgetRef(delRefs[i]) persistentRefs = {} createRefs = {} for o in refs: if (o not in self.startRefs): if (o not in self.newRefs): createRefs[o] = refs[o] else: persistentRefs[o] = refs[o] for r in self.newRefs: self.forgetRef(self.newRefs[r]) self.newRefs.clear() self.newRefs.update(persistentRefs) self.newRefs.update(createRefs) for r in self.newRefs: self.rememberRef(self.newRefs[r]) self.persistentRefs.clear() self.persistentRefs.update(persistentRefs) print('----------- Count changes since start: ----------') c1 = count.copy() for k in self.startCount: c1[k] = (c1.get(k, 0) - self.startCount[k]) typs = list(c1.keys()) typs.sort(key=(lambda a: c1[a])) for t in typs: if (c1[t] == 0): continue num = ('%d' % c1[t]) print((((' ' + num) + (' ' * (10 - len(num)))) + str(t))) print(('----------- %d Deleted since last diff: ------------' % len(delRefs))) self.report(delRefs, objs, **kargs) print(('----------- %d Created since last diff: ------------' % len(createRefs))) self.report(createRefs, objs, **kargs) print(('----------- %d Created since start (persistent): ------------' % len(persistentRefs))) self.report(persistentRefs, objs, **kargs)
'**Arguments:** name Optional name for this process used when printing messages from the remote process. target Optional function to call after starting remote process. By default, this is startEventLoop(), which causes the remote process to process requests from the parent process until it is asked to quit. If you wish to specify a different target, it must be picklable (bound methods are not). copySysPath If True, copy the contents of sys.path to the remote process debug If True, print detailed information about communication with the child process. wrapStdout If True (default on windows) then stdout and stderr from the child process will be caught by the parent process and forwarded to its stdout/stderr. This provides a workaround for a python bug: http://bugs.python.org/issue3905 but has the side effect that child output is significantly delayed relative to the parent output.'
def __init__(self, name=None, target=None, executable=None, copySysPath=True, debug=False, timeout=20, wrapStdout=None):
if (target is None): target = startEventLoop if (name is None): name = str(self) if (executable is None): executable = sys.executable self.debug = (7 if (debug is True) else False) authkey = os.urandom(20) if sys.platform.startswith('win'): authkey = None l = multiprocessing.connection.Listener(('localhost', 0), authkey=authkey) port = l.address[1] sysPath = (sys.path if copySysPath else None) bootstrap = os.path.abspath(os.path.join(os.path.dirname(__file__), 'bootstrap.py')) self.debugMsg(('Starting child process (%s %s)' % (executable, bootstrap))) if debug: procDebug = ((Process._process_count % 6) + 1) Process._process_count += 1 else: procDebug = False if (wrapStdout is None): wrapStdout = sys.platform.startswith('win') if wrapStdout: stdout = subprocess.PIPE stderr = subprocess.PIPE self.proc = subprocess.Popen((executable, bootstrap), stdin=subprocess.PIPE, stdout=stdout, stderr=stderr) self._stdoutForwarder = FileForwarder(self.proc.stdout, 'stdout', procDebug) self._stderrForwarder = FileForwarder(self.proc.stderr, 'stderr', procDebug) else: self.proc = subprocess.Popen((executable, bootstrap), stdin=subprocess.PIPE) targetStr = pickle.dumps(target) pid = os.getpid() data = dict(name=(name + '_child'), port=port, authkey=authkey, ppid=pid, targetStr=targetStr, path=sysPath, pyside=USE_PYSIDE, debug=procDebug) pickle.dump(data, self.proc.stdin) self.proc.stdin.close() self.debugMsg(('Listening for child process on port %d, authkey=%s..' % (port, repr(authkey)))) while True: try: conn = l.accept() break except IOError as err: if (err.errno == 4): continue else: raise RemoteEventHandler.__init__(self, conn, (name + '_parent'), pid=self.proc.pid, debug=self.debug) self.debugMsg('Connected to child process.') atexit.register(self.join)
'When initializing, an optional target may be given. If no target is specified, self.eventLoop will be used. If None is given, no target will be called (and it will be up to the caller to properly shut down the forked process) preProxy may be a dict of values that will appear as ObjectProxy in the remote process (but do not need to be sent explicitly since they are available immediately before the call to fork(). Proxies will be availabe as self.proxies[name]. If randomReseed is True, the built-in random and numpy.random generators will be reseeded in the child process.'
def __init__(self, name=None, target=0, preProxy=None, randomReseed=True):
self.hasJoined = False if (target == 0): target = self.eventLoop if (name is None): name = str(self) (conn, remoteConn) = multiprocessing.Pipe() proxyIDs = {} if (preProxy is not None): for (k, v) in preProxy.iteritems(): proxyId = LocalObjectProxy.registerObject(v) proxyIDs[k] = proxyId ppid = os.getpid() pid = os.fork() if (pid == 0): self.isParent = False os.setpgrp() conn.close() sys.stdin.close() fid = remoteConn.fileno() os.closerange(3, fid) os.closerange((fid + 1), 4096) def excepthook(*args): import traceback traceback.print_exception(*args) sys.excepthook = excepthook for qtlib in ('PyQt4', 'PySide', 'PyQt5'): if (qtlib in sys.modules): sys.modules[(qtlib + '.QtGui')].QApplication = None sys.modules.pop((qtlib + '.QtGui'), None) sys.modules.pop((qtlib + '.QtCore'), None) atexit._exithandlers = [] atexit.register((lambda : os._exit(0))) if randomReseed: if ('numpy.random' in sys.modules): sys.modules['numpy.random'].seed((os.getpid() ^ int(((time.time() * 10000) % 10000)))) if ('random' in sys.modules): sys.modules['random'].seed((os.getpid() ^ int(((time.time() * 10000) % 10000)))) RemoteEventHandler.__init__(self, remoteConn, (name + '_child'), pid=ppid) self.forkedProxies = {} for (name, proxyId) in proxyIDs.iteritems(): self.forkedProxies[name] = ObjectProxy(ppid, proxyId=proxyId, typeStr=repr(preProxy[name])) if (target is not None): target() else: self.isParent = True self.childPid = pid remoteConn.close() RemoteEventHandler.handlers = {} RemoteEventHandler.__init__(self, conn, (name + '_parent'), pid=pid) atexit.register(self.join)
'Immediately kill the forked remote process. This is generally safe because forked processes are already expected to _avoid_ any cleanup at exit.'
def kill(self):
os.kill(self.childPid, signal.SIGKILL) self.hasJoined = True
'Start listening for requests coming from the child process. This allows signals to be connected from the child process to the parent.'
def startRequestProcessing(self, interval=0.01):
self.timer.timeout.connect(self.processRequests) self.timer.start((interval * 1000))
'Set the default behavior options for object proxies. See ObjectProxy._setProxyOptions for more info.'
def setProxyOptions(self, **kwds):
with self.optsLock: self.proxyOptions.update(kwds)
'Process all pending requests from the pipe, return after no more events are immediately available. (non-blocking) Returns the number of events processed.'
def processRequests(self):
with self.processLock: if self.exited: self.debugMsg(' processRequests: exited already; raise ClosedError.') raise ClosedError() numProcessed = 0 while self.conn.poll(): try: self.handleRequest() numProcessed += 1 except ClosedError: self.debugMsg('processRequests: got ClosedError from handleRequest; setting exited=True.') self.exited = True raise except: print ('Error in process %s' % self.name) sys.excepthook(*sys.exc_info()) if (numProcessed > 0): self.debugMsg('processRequests: finished %d requests', numProcessed) return numProcessed
'Handle a single request from the remote process. Blocks until a request is available.'
def handleRequest(self):
result = None while True: try: (cmd, reqId, nByteMsgs, optStr) = self.conn.recv() break except EOFError: self.debugMsg(' handleRequest: got EOFError from recv; raise ClosedError.') raise ClosedError() except IOError as err: if (err.errno == 4): self.debugMsg(' handleRequest: got IOError 4 from recv; try again.') continue else: self.debugMsg(' handleRequest: got IOError %d from recv (%s); raise ClosedError.', err.errno, err.strerror) raise ClosedError() self.debugMsg(' handleRequest: received %s %s', cmd, reqId) byteData = [] if (nByteMsgs > 0): self.debugMsg(' handleRequest: reading %d byte messages', nByteMsgs) for i in range(nByteMsgs): while True: try: byteData.append(self.conn.recv_bytes()) break except EOFError: self.debugMsg(' handleRequest: got EOF while reading byte messages; raise ClosedError.') raise ClosedError() except IOError as err: if (err.errno == 4): self.debugMsg(' handleRequest: got IOError 4 while reading byte messages; try again.') continue else: self.debugMsg(' handleRequest: got IOError while reading byte messages; raise ClosedError.') raise ClosedError() try: if ((cmd == 'result') or (cmd == 'error')): resultId = reqId reqId = None opts = pickle.loads(optStr) self.debugMsg(' handleRequest: id=%s opts=%s', reqId, opts) returnType = opts.get('returnType', 'auto') if (cmd == 'result'): with self.resultLock: self.results[resultId] = ('result', opts['result']) elif (cmd == 'error'): with self.resultLock: self.results[resultId] = ('error', (opts['exception'], opts['excString'])) elif (cmd == 'getObjAttr'): result = getattr(opts['obj'], opts['attr']) elif (cmd == 'callObj'): obj = opts['obj'] fnargs = opts['args'] fnkwds = opts['kwds'] if (len(byteData) > 0): for (i, arg) in enumerate(fnargs): if (isinstance(arg, tuple) and (len(arg) > 0) and (arg[0] == '__byte_message__')): ind = arg[1] (dtype, shape) = arg[2] fnargs[i] = np.fromstring(byteData[ind], dtype=dtype).reshape(shape) for (k, arg) in fnkwds.items(): if (isinstance(arg, tuple) and (len(arg) > 0) and (arg[0] == '__byte_message__')): ind = arg[1] (dtype, shape) = arg[2] fnkwds[k] = np.fromstring(byteData[ind], dtype=dtype).reshape(shape) if (len(fnkwds) == 0): try: result = obj(*fnargs) except: print ('Failed to call object %s: %d, %s' % (obj, len(fnargs), fnargs[1:])) raise else: result = obj(*fnargs, **fnkwds) elif (cmd == 'getObjValue'): result = opts['obj'] returnType = 'value' elif (cmd == 'transfer'): result = opts['obj'] returnType = 'proxy' elif (cmd == 'transferArray'): result = np.fromstring(byteData[0], dtype=opts['dtype']).reshape(opts['shape']) returnType = 'proxy' elif (cmd == 'import'): name = opts['module'] fromlist = opts.get('fromlist', []) mod = builtins.__import__(name, fromlist=fromlist) if (len(fromlist) == 0): parts = name.lstrip('.').split('.') result = mod for part in parts[1:]: result = getattr(result, part) else: result = map(mod.__getattr__, fromlist) elif (cmd == 'del'): LocalObjectProxy.releaseProxyId(opts['proxyId']) elif (cmd == 'close'): if (reqId is not None): result = True returnType = 'value' exc = None except: exc = sys.exc_info() if (reqId is not None): if (exc is None): self.debugMsg(' handleRequest: sending return value for %d: %s', reqId, result) if (returnType == 'auto'): with self.optsLock: noProxyTypes = self.proxyOptions['noProxyTypes'] result = self.autoProxy(result, noProxyTypes) elif (returnType == 'proxy'): result = LocalObjectProxy(result) try: self.replyResult(reqId, result) except: sys.excepthook(*sys.exc_info()) self.replyError(reqId, *sys.exc_info()) else: self.debugMsg(' handleRequest: returning exception for %d', reqId) self.replyError(reqId, *exc) elif (exc is not None): sys.excepthook(*exc) if (cmd == 'close'): if (opts.get('noCleanup', False) is True): os._exit(0) else: raise ClosedError()
'Send a request or return packet to the remote process. Generally it is not necessary to call this method directly; it is for internal use. (The docstring has information that is nevertheless useful to the programmer as it describes the internal protocol used to communicate between processes) **Arguments:** request String describing the type of request being sent (see below) reqId Integer uniquely linking a result back to the request that generated it. (most requests leave this blank) callSync \'sync\': return the actual result of the request \'async\': return a Request object which can be used to look up the result later \'off\': return no result timeout Time in seconds to wait for a response when callSync==\'sync\' opts Extra arguments sent to the remote process that determine the way the request will be handled (see below) returnType \'proxy\', \'value\', or \'auto\' byteData If specified, this is a list of objects to be sent as byte messages to the remote process. This is used to send large arrays without the cost of pickling. Description of request strings and options allowed for each: request option description getObjAttr Request the remote process return (proxy to) an attribute of an object. obj reference to object whose attribute should be returned attr string name of attribute to return returnValue bool or \'auto\' indicating whether to return a proxy or the actual value. callObj Request the remote process call a function or method. If a request ID is given, then the call\'s return value will be sent back (or information about the error that occurred while running the function) obj the (reference to) object to call args tuple of arguments to pass to callable kwds dict of keyword arguments to pass to callable returnValue bool or \'auto\' indicating whether to return a proxy or the actual value. getObjValue Request the remote process return the value of a proxied object (must be picklable) obj reference to object whose value should be returned transfer Copy an object to the remote process and request it return a proxy for the new object. obj The object to transfer. import Request the remote process import new symbols and return proxy(ies) to the imported objects module the string name of the module to import fromlist optional list of string names to import from module del Inform the remote process that a proxy has been released (thus the remote process may be able to release the original object) proxyId id of proxy which is no longer referenced by remote host close Instruct the remote process to stop its event loop and exit. Optionally, this request may return a confirmation. result Inform the remote process that its request has been processed result return value of a request error Inform the remote process that its request failed exception the Exception that was raised (or None if the exception could not be pickled) excString string-formatted version of the exception and traceback'
def send(self, request, opts=None, reqId=None, callSync='sync', timeout=10, returnType=None, byteData=None, **kwds):
if self.exited: self.debugMsg(' send: exited already; raise ClosedError.') raise ClosedError() with self.sendLock: if (opts is None): opts = {} assert (callSync in ['off', 'sync', 'async']), 'callSync must be one of "off", "sync", or "async"' if (reqId is None): if (callSync != 'off'): reqId = self.nextRequestId self.nextRequestId += 1 else: assert (request in ['result', 'error']) if (returnType is not None): opts['returnType'] = returnType try: optStr = pickle.dumps(opts) except: print '==== Error pickling this object: ====' print opts print '=======================================' raise nByteMsgs = 0 if (byteData is not None): nByteMsgs = len(byteData) request = (request, reqId, nByteMsgs, optStr) self.debugMsg('send request: cmd=%s nByteMsgs=%d id=%s opts=%s', request[0], nByteMsgs, reqId, opts) self.conn.send(request) if (byteData is not None): for obj in byteData: self.conn.send_bytes(obj) self.debugMsg(' sent %d byte messages', len(byteData)) self.debugMsg(' call sync: %s', callSync) if (callSync == 'off'): return req = Request(self, reqId, description=str(request), timeout=timeout) if (callSync == 'async'): return req if (callSync == 'sync'): try: return req.result() except NoResultError: return req
'Request the remote process import a module (or symbols from a module) and return the proxied results. Uses built-in __import__() function, but adds a bit more processing: _import(\'module\') => returns module _import(\'module.submodule\') => returns submodule (note this differs from behavior of __import__) _import(\'module\', fromlist=[name1, name2, ...]) => returns [module.name1, module.name2, ...] (this also differs from behavior of __import__)'
def _import(self, mod, **kwds):
return self.send(request='import', callSync='sync', opts=dict(module=mod), **kwds)
'Transfer an object by value to the remote host (the object must be picklable) and return a proxy for the new remote object.'
def transfer(self, obj, **kwds):
if (obj.__class__ is np.ndarray): opts = {'dtype': obj.dtype, 'shape': obj.shape} return self.send(request='transferArray', opts=opts, byteData=[obj], **kwds) else: return self.send(request='transfer', opts=dict(obj=obj), **kwds)
'Return the result for this request. If block is True, wait until the result has arrived or *timeout* seconds passes. If the timeout is reached, raise NoResultError. (use timeout=None to disable) If block is False, raise NoResultError immediately if the result has not arrived yet. If the process\'s connection has closed before the result arrives, raise ClosedError.'
def result(self, block=True, timeout=None):
if self.gotResult: return self._result if (timeout is None): timeout = self.timeout if block: start = time.time() while (not self.hasResult()): if self.proc.exited: raise ClosedError() time.sleep(0.005) if ((timeout >= 0) and ((time.time() - start) > timeout)): print ('Request timed out: %s' % self.description) import traceback traceback.print_stack() raise NoResultError() return self._result else: self._result = self.proc.getResult(self.reqId) self.gotResult = True return self._result
'Returns True if the result for this request has arrived.'
def hasResult(self):
try: self.result(block=False) except NoResultError: pass return self.gotResult
'Create a \'local\' proxy object that, when sent to a remote host, will appear as a normal ObjectProxy to *obj*. Any extra keyword arguments are passed to proxy._setProxyOptions() on the remote side.'
def __init__(self, obj, **opts):
self.processId = os.getpid() self.typeStr = repr(obj) self.obj = obj self.opts = opts
'Change the behavior of this proxy. For all options, a value of None will cause the proxy to instead use the default behavior defined by its parent Process. Options are: callSync \'sync\', \'async\', \'off\', or None. If \'async\', then calling methods will return a Request object which can be used to inquire later about the result of the method call. If \'sync\', then calling a method will block until the remote process has returned its result or the timeout has elapsed (in this case, a Request object is returned instead). If \'off\', then the remote process is instructed _not_ to reply and the method call will return None immediately. returnType \'auto\', \'proxy\', \'value\', or None. If \'proxy\', then the value returned when calling a method will be a proxy to the object on the remote process. If \'value\', then attempt to pickle the returned object and send it back. If \'auto\', then the decision is made by consulting the \'noProxyTypes\' option. autoProxy bool or None. If True, arguments to __call__ are automatically converted to proxy unless their type is listed in noProxyTypes (see below). If False, arguments are left untouched. Use proxy(obj) to manually convert arguments before sending. timeout float or None. Length of time to wait during synchronous requests before returning a Request object instead. deferGetattr True, False, or None. If False, all attribute requests will be sent to the remote process immediately and will block until a response is received (or timeout has elapsed). If True, requesting an attribute from the proxy returns a new proxy immediately. The remote process is _not_ contacted to make this request. This is faster, but it is possible to request an attribute that does not exist on the proxied object. In this case, AttributeError will not be raised until an attempt is made to look up the attribute on the remote process. noProxyTypes List of object types that should _not_ be proxied when sent to the remote process.'
def _setProxyOptions(self, **kwds):
for k in kwds: if (k not in self._proxyOptions): raise KeyError(("Unrecognized proxy option '%s'" % k)) self._proxyOptions.update(kwds)
'Return the value of the proxied object (the remote object must be picklable)'
def _getValue(self):
return self._handler.getObjValue(self)