From 2daa8e5d9698850947c8b06cd4b627dea89c4155 Mon Sep 17 00:00:00 2001 From: Dave Date: Mon, 13 Nov 2017 23:08:48 -0600 Subject: [PATCH] update to python3 and pyqt5 Used 2to3 to update to python3 made small changes for compatibility, mainly encode/decode for byte strings also change from buffer to memoryview Additionally upgraded to pyqt5 as pyqt4 support seems to be deprecated in many new python distributions, just renaming of and relocating of various packages/classes, no real changes --- README.md | 2 +- liveplot/__init__.py | 2 +- liveplot/__main__.py | 2 +- liveplot/client.py | 12 ++++++------ liveplot/widgets.py | 26 +++++++++++++------------- liveplot/window.py | 32 ++++++++++++++++---------------- liveplot_test.py | 10 +++++----- 7 files changed, 43 insertions(+), 43 deletions(-) diff --git a/README.md b/README.md index 9ac89cf..5b65718 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ it is overwritten. Requirements ------------ - Numpy -- [PyQt4](http://www.riverbankcomputing.com/software/pyqt/download) +- [PyQt5](http://www.riverbankcomputing.com/software/pyqt/download) - [pyqtgraph](http://www.pyqtgraph.org) pyqtgraph will be installed automatically from PyPI if not found diff --git a/liveplot/__init__.py b/liveplot/__init__.py index 31e94eb..c936f88 100644 --- a/liveplot/__init__.py +++ b/liveplot/__init__.py @@ -1 +1 @@ -from client import LivePlotClient +from .client import LivePlotClient diff --git a/liveplot/__main__.py b/liveplot/__main__.py index fabb44f..b323945 100644 --- a/liveplot/__main__.py +++ b/liveplot/__main__.py @@ -1,2 +1,2 @@ -from window import main +from .window import main main() \ No newline at end of file diff --git a/liveplot/client.py b/liveplot/client.py index 90aae0e..968b9c2 100644 --- a/liveplot/client.py +++ b/liveplot/client.py @@ -4,15 +4,15 @@ import warnings import numpy as np import logging -from PyQt4.QtNetwork import QLocalSocket -from PyQt4.QtCore import QCoreApplication, QSharedMemory +from PyQt5.QtNetwork import QLocalSocket +from PyQt5.QtCore import QCoreApplication, QSharedMemory __author__ = 'phil' logging.root.setLevel(logging.WARNING) class LivePlotClient(object): - def __init__(self, timeout=2000, size=2**20): + def __init__(self, timeout=2000, size=2**28): self.app = QCoreApplication.instance() if self.app is None: self.app = QCoreApplication([]) @@ -27,7 +27,7 @@ def __init__(self, timeout=2000, size=2**20): if not self.shared_mem.create(size): raise Exception("Couldn't create shared memory %s" % self.shared_mem.errorString()) logging.debug('Memory created with key %s and size %s' % (key, self.shared_mem.size())) - self.sock.write(key) + self.sock.write(key.encode()) self.sock.waitForBytesWritten() self.is_connected = True @@ -59,13 +59,13 @@ def send_to_plotter(self, meta, arr=None): raise ValueError("meta object is too large (> 200 char)") if arr is None: - self.sock.write(meta_bytes) + self.sock.write(meta_bytes.encode()) else: if not self.sock.bytesAvailable(): self.sock.waitForReadyRead() self.sock.read(2) self.shared_mem.lock() - self.sock.write(meta_bytes) + self.sock.write(meta_bytes.encode()) region = self.shared_mem.data() region[:arrsize] = arrbytes self.shared_mem.unlock() diff --git a/liveplot/widgets.py b/liveplot/widgets.py index f7c7123..973bb1c 100644 --- a/liveplot/widgets.py +++ b/liveplot/widgets.py @@ -1,4 +1,4 @@ -from PyQt4 import QtGui, QtCore +from PyQt5 import QtWidgets, QtCore import warnings import pyqtgraph as pg import numpy as np @@ -14,16 +14,16 @@ class CloseableDock(Dock): docklist = [] def __init__(self, *args, **kwargs): super(CloseableDock, self).__init__(*args, **kwargs) - style = QtGui.QStyleFactory().create("windows") - close_icon = style.standardIcon(QtGui.QStyle.SP_TitleBarCloseButton) - close_button = QtGui.QPushButton(close_icon, "", self) + style = QtWidgets.QStyleFactory().create("windows") + close_icon = style.standardIcon(QtWidgets.QStyle.SP_TitleBarCloseButton) + close_button = QtWidgets.QPushButton(close_icon, "", self) close_button.clicked.connect(self.close) close_button.setGeometry(0, 0, 20, 20) close_button.raise_() self.closeClicked = close_button.clicked - max_icon = style.standardIcon(QtGui.QStyle.SP_TitleBarMaxButton) - max_button = QtGui.QPushButton(max_icon, "", self) + max_icon = style.standardIcon(QtWidgets.QStyle.SP_TitleBarMaxButton) + max_button = QtWidgets.QPushButton(max_icon, "", self) max_button.clicked.connect(self.maximize) max_button.setGeometry(20, 0, 20, 20) max_button.raise_() @@ -77,7 +77,7 @@ def handle_mouse_move(self, mouse_event): xdata, ydata = data_item.xData, data_item.yData index_distance = lambda i: (xdata[i]-view_x)**2 + (ydata[i] - view_y)**2 if self.parametric: - index = min(range(len(xdata)), key=index_distance) + index = min(list(range(len(xdata))), key=index_distance) else: index = min(np.searchsorted(xdata, view_x), len(xdata)-1) if index and xdata[index] - view_x > view_x - xdata[index - 1]: @@ -163,19 +163,19 @@ def __init__(self, trace_size=80, **kwargs): self.search_mode = False self.signals_connected = False self.set_histogram(False) - histogram_action = QtGui.QAction('Histogram', self) + histogram_action = QtWidgets.QAction('Histogram', self) histogram_action.setCheckable(True) histogram_action.triggered.connect(self.set_histogram) self.img_view.scene.contextMenu.append(histogram_action) - self.autolevels_action = QtGui.QAction('Autoscale Levels', self) + self.autolevels_action = QtWidgets.QAction('Autoscale Levels', self) self.autolevels_action.setCheckable(True) self.autolevels_action.setChecked(True) self.autolevels_action.triggered.connect(self.redraw) self.ui.histogram.item.sigLevelChangeFinished.connect(lambda: self.autolevels_action.setChecked(False)) self.img_view.scene.contextMenu.append(self.autolevels_action) - self.clear_action = QtGui.QAction('Clear Contents', self) + self.clear_action = QtWidgets.QAction('Clear Contents', self) self.clear_action.triggered.connect(self.clear) self.img_view.scene.contextMenu.append(self.clear_action) @@ -200,7 +200,7 @@ def __init__(self, trace_size=80, **kwargs): self.v_cross_section_widget_data = self.v_cross_section_widget.plot([0,0]) def setLabels(self, xlabel="X", ylabel="Y", zlabel="Z"): - print self.h_cross_dock.label + print(self.h_cross_dock.label) self.plot_item.setLabels(bottom=(xlabel,), left=(ylabel,)) self.h_cross_section_widget.plotItem.setLabels(bottom=xlabel, left=zlabel) self.v_cross_section_widget.plotItem.setLabels(bottom=ylabel, left=zlabel) @@ -341,8 +341,8 @@ def __init__(self, array, *args, **kwargs): super(MoviePlotDock, self).__init__(*args, **kwargs) self.setImage(array) self.tpts = len(array) - play_button = QtGui.QPushButton("Play") - stop_button = QtGui.QPushButton("Stop") + play_button = QtWidgets.QPushButton("Play") + stop_button = QtWidgets.QPushButton("Stop") stop_button.hide() self.addWidget(play_button) self.addWidget(stop_button) diff --git a/liveplot/window.py b/liveplot/window.py index 8ad81ff..1e58970 100644 --- a/liveplot/window.py +++ b/liveplot/window.py @@ -3,13 +3,13 @@ import json import logging import signal -import widgets +from . import widgets import numpy as np -from PyQt4.QtCore import QSharedMemory, QSize -from PyQt4.QtGui import QMainWindow, QApplication, QStandardItem, QDockWidget, QStandardItemModel, QListView, QAction, \ - QIcon -from PyQt4.QtNetwork import QLocalServer -from PyQt4.Qt import Qt as QtConst +from PyQt5.QtCore import QSharedMemory, QSize +from PyQt5.QtWidgets import QMainWindow, QApplication, QDockWidget, QListView, QAction +from PyQt5.QtGui import QStandardItem,QStandardItemModel, QIcon +from PyQt5.QtNetwork import QLocalServer +from PyQt5.Qt import Qt as QtConst from pyqtgraph.dockarea import DockArea logging.root.setLevel(logging.WARNING) @@ -38,7 +38,7 @@ def __init__(self): def close(self, sig=None, frame=None): - print 'closing' + print('closing') for conn in self.conns: conn.close() for shm in self.shared_mems: @@ -50,7 +50,7 @@ def accept(self): logging.debug('connection accepted') conn = self.server.nextPendingConnection() conn.waitForReadyRead() - key = str(conn.read(36)) + key = str(conn.read(36).decode()) memory = QSharedMemory() memory.setKey(key) memory.attach() @@ -60,18 +60,18 @@ def accept(self): self.shared_mems.append(memory) conn.readyRead.connect(lambda: self.read_from(conn, memory)) conn.disconnected.connect(memory.detach) - conn.write('ok') + conn.write(b'ok') # noinspection PyNoneFunctionAssignment def read_from(self, conn, memory): logging.debug('reading data') - self.meta = json.loads(conn.read(200)) + self.meta = json.loads(conn.read(200).decode()) if self.meta['arrsize'] != 0: memory.lock() ba = memory.data()[0:self.meta['arrsize']] - arr = np.frombuffer(buffer(ba)) + arr = np.frombuffer(memoryview(ba)) memory.unlock() - conn.write('ok') + conn.write(b'ok') arr = arr.reshape(self.meta['shape']).copy() else: arr = None @@ -126,11 +126,11 @@ def remove(name): elif name == "*": if operation == 'clear': - map(clear, self.namelist.keys()) + list(map(clear, list(self.namelist.keys()))) elif operation == 'close': - map(close, self.namelist.keys()) + list(map(close, list(self.namelist.keys()))) elif operation == 'remove': - map(remove, self.namelist.keys()) + list(map(remove, list(self.namelist.keys()))) return else: if operation in ('clear', 'close', 'remove'): @@ -266,7 +266,7 @@ def __delitem__(self, name): del self.plot_dict[name] def keys(self): - return self.plot_dict.keys(); + return list(self.plot_dict.keys()); def main(): diff --git a/liveplot_test.py b/liveplot_test.py index 4900966..8e2824a 100644 --- a/liveplot_test.py +++ b/liveplot_test.py @@ -1,6 +1,6 @@ import inspect -from PyQt4.QtCore import QTimer -from PyQt4.QtGui import QApplication, QWidget, QVBoxLayout, QSpinBox, QHBoxLayout, QLabel, QPushButton, \ +from PyQt5.QtCore import QTimer +from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QSpinBox, QHBoxLayout, QLabel, QPushButton, \ QPlainTextEdit, QProgressBar import numpy as np import sys @@ -124,7 +124,7 @@ def set_iterator(): self.timer.start() return set_iterator - for name, iter in tests.items(): + for name, iter in list(tests.items()): button = QPushButton(name) button.clicked.connect(make_set_iterator(iter)) button_layout.addWidget(button) @@ -137,7 +137,7 @@ def set_iterator(): def iterate(self): try: - self.iterator.next() + next(self.iterator) self.progress_bar.setValue(self.progress_bar.value() + 1) except StopIteration: self.timer.stop() @@ -145,7 +145,7 @@ def iterate(self): if __name__ == "__main__": app = QApplication([]) - c = LivePlotClient(size=2**20) + c = LivePlotClient(size=2**28) win = TestWindow() win.show() def clean():