Qulogic py3 fixes (#1073)

* py3k: Remove reduce calls.

* py3k: Remove compatibility sortList function.

Sorting by key has existed since Python 2.4.

* Remove unnecessary sys.path manipulation.

This file doesn't have any __main__ code to run anyway.

* Use context manager
This commit is contained in:
Kenneth Lyons 2019-11-12 08:45:42 -08:00 committed by Ogi Moore
parent f5e25622a7
commit faef56c3e7
18 changed files with 163 additions and 182 deletions

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
import weakref import weakref
from ..Qt import QtCore, QtGui from ..Qt import QtCore, QtGui
from ..python2_3 import sortList, cmp
from ..Point import Point from ..Point import Point
from .. import functions as fn from .. import functions as fn
from .. import ptime as ptime from .. import ptime as ptime
@ -454,7 +454,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
return 0 return 0
return item.zValue() + absZValue(item.parentItem()) return item.zValue() + absZValue(item.parentItem())
sortList(items2, lambda a,b: cmp(absZValue(b), absZValue(a))) items2.sort(key=absZValue, reverse=True)
return items2 return items2
@ -563,6 +563,3 @@ class GraphicsScene(QtGui.QGraphicsScene):
@staticmethod @staticmethod
def translateGraphicsItems(items): def translateGraphicsItems(items):
return list(map(GraphicsScene.translateGraphicsItem, items)) return list(map(GraphicsScene.translateGraphicsItem, items))

View File

@ -95,7 +95,8 @@ def systemInfo():
if __version__ is None: ## this code was probably checked out from bzr; look up the last-revision file if __version__ is None: ## this code was probably checked out from bzr; look up the last-revision file
lastRevFile = os.path.join(os.path.dirname(__file__), '..', '.bzr', 'branch', 'last-revision') lastRevFile = os.path.join(os.path.dirname(__file__), '..', '.bzr', 'branch', 'last-revision')
if os.path.exists(lastRevFile): if os.path.exists(lastRevFile):
rev = open(lastRevFile, 'r').read().strip() with open(lastRevFile, 'r') as fd:
rev = fd.read().strip()
print("pyqtgraph: %s; %s" % (__version__, rev)) print("pyqtgraph: %s; %s" % (__version__, rev))
print("config:") print("config:")

View File

@ -1,8 +1,4 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
if __name__ == '__main__':
import sys, os
md = os.path.dirname(os.path.abspath(__file__))
sys.path = [os.path.dirname(md), os.path.join(md, '..', '..', '..')] + sys.path
from ..Qt import QtGui, QtCore, QT_LIB from ..Qt import QtGui, QtCore, QT_LIB
from ..graphicsItems.ROI import ROI from ..graphicsItems.ROI import ROI

View File

@ -39,9 +39,9 @@ class ParseError(Exception):
def writeConfigFile(data, fname): def writeConfigFile(data, fname):
s = genString(data) s = genString(data)
fd = open(fname, 'w') with open(fname, 'w') as fd:
fd.write(s) fd.write(s)
fd.close()
def readConfigFile(fname): def readConfigFile(fname):
#cwd = os.getcwd() #cwd = os.getcwd()
@ -55,9 +55,8 @@ def readConfigFile(fname):
try: try:
#os.chdir(newDir) ## bad. #os.chdir(newDir) ## bad.
fd = open(fname) with open(fname) as fd:
s = asUnicode(fd.read()) s = asUnicode(fd.read())
fd.close()
s = s.replace("\r\n", "\n") s = s.replace("\r\n", "\n")
s = s.replace("\r", "\n") s = s.replace("\r", "\n")
data = parseString(s)[1] data = parseString(s)[1]
@ -73,9 +72,8 @@ def readConfigFile(fname):
def appendConfigFile(data, fname): def appendConfigFile(data, fname):
s = genString(data) s = genString(data)
fd = open(fname, 'a') with open(fname, 'a') as fd:
fd.write(s) fd.write(s)
fd.close()
def genString(data, indent=''): def genString(data, indent=''):
@ -194,8 +192,6 @@ def measureIndent(s):
if __name__ == '__main__': if __name__ == '__main__':
import tempfile import tempfile
fn = tempfile.mktemp()
tf = open(fn, 'w')
cf = """ cf = """
key: 'value' key: 'value'
key2: ##comment key2: ##comment
@ -205,8 +201,9 @@ key2: ##comment
key22: [1,2,3] key22: [1,2,3]
key23: 234 #comment key23: 234 #comment
""" """
fn = tempfile.mktemp()
with open(fn, 'w') as tf:
tf.write(cf) tf.write(cf)
tf.close()
print("=== Test:===") print("=== Test:===")
num = 1 num = 1
for line in cf.split('\n'): for line in cf.split('\n'):

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
import sys, re, os, time, traceback, subprocess import sys, re, os, time, traceback, subprocess
import pickle import pickle
@ -98,12 +99,14 @@ class ConsoleWidget(QtGui.QWidget):
def loadHistory(self): def loadHistory(self):
"""Return the list of previously-invoked command strings (or None).""" """Return the list of previously-invoked command strings (or None)."""
if self.historyFile is not None: if self.historyFile is not None:
return pickle.load(open(self.historyFile, 'rb')) with open(self.historyFile, 'rb') as pf:
return pickle.load(pf)
def saveHistory(self, history): def saveHistory(self, history):
"""Store the list of previously-invoked command strings.""" """Store the list of previously-invoked command strings."""
if self.historyFile is not None: if self.historyFile is not None:
pickle.dump(open(self.historyFile, 'wb'), history) with open(self.historyFile, 'wb') as pf:
pickle.dump(pf, history)
def runCmd(self, cmd): def runCmd(self, cmd):
self.stdout = sys.stdout self.stdout = sys.stdout

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore from ..Qt import QtGui, QtCore
from .Exporter import Exporter from .Exporter import Exporter
from ..parametertree import Parameter from ..parametertree import Parameter
@ -29,7 +30,6 @@ class CSVExporter(Exporter):
self.fileSaveDialog(filter=["*.csv", "*.tsv"]) self.fileSaveDialog(filter=["*.csv", "*.tsv"])
return return
fd = open(fileName, 'w')
data = [] data = []
header = [] header = []
@ -56,14 +56,15 @@ class CSVExporter(Exporter):
else: else:
sep = '\t' sep = '\t'
with open(fileName, 'w') as fd:
fd.write(sep.join(header) + '\n') fd.write(sep.join(header) + '\n')
i = 0 i = 0
numFormat = '%%0.%dg' % self.params['precision'] numFormat = '%%0.%dg' % self.params['precision']
numRows = max([len(d[0]) for d in data]) numRows = max([len(d[0]) for d in data])
for i in range(numRows): for i in range(numRows):
for j, d in enumerate(data): for j, d in enumerate(data):
# write x value if this is the first column, or if we want x # write x value if this is the first column, or if we want
# for all rows # x for all rows
if appendAllX or j == 0: if appendAllX or j == 0:
if d is not None and i < len(d[0]): if d is not None and i < len(d[0]):
fd.write(numFormat % d[0][i] + sep) fd.write(numFormat % d[0][i] + sep)
@ -76,7 +77,7 @@ class CSVExporter(Exporter):
else: else:
fd.write(' %s' % sep) fd.write(' %s' % sep)
fd.write('\n') fd.write('\n')
fd.close()
CSVExporter.register() CSVExporter.register()

View File

@ -1,14 +1,14 @@
# -*- coding: utf-8 -*-
import operator
import weakref import weakref
import numpy as np import numpy as np
from ..Qt import QtGui, QtCore from ..Qt import QtGui, QtCore
from ..python2_3 import sortList
from .. import functions as fn from .. import functions as fn
from .GraphicsObject import GraphicsObject from .GraphicsObject import GraphicsObject
from .GraphicsWidget import GraphicsWidget from .GraphicsWidget import GraphicsWidget
from ..widgets.SpinBox import SpinBox from ..widgets.SpinBox import SpinBox
from ..pgcollections import OrderedDict from ..pgcollections import OrderedDict
from ..colormap import ColorMap from ..colormap import ColorMap
from ..python2_3 import cmp
__all__ = ['TickSliderItem', 'GradientEditorItem'] __all__ = ['TickSliderItem', 'GradientEditorItem']
@ -352,8 +352,7 @@ class TickSliderItem(GraphicsWidget):
def listTicks(self): def listTicks(self):
"""Return a sorted list of all the Tick objects on the slider.""" """Return a sorted list of all the Tick objects on the slider."""
## public ## public
ticks = list(self.ticks.items()) ticks = sorted(self.ticks.items(), key=operator.itemgetter(1))
sortList(ticks, lambda a,b: cmp(a[1], b[1])) ## see pyqtgraph.python2_3.sortList
return ticks return ticks
@ -944,4 +943,3 @@ class TickMenu(QtGui.QMenu):
# self.fracPosSpin.blockSignals(True) # self.fracPosSpin.blockSignals(True)
# self.fracPosSpin.setValue(self.sliderItem().tickValue(self.tick())) # self.fracPosSpin.setValue(self.sliderItem().tickValue(self.tick()))
# self.fracPosSpin.blockSignals(False) # self.fracPosSpin.blockSignals(False)

View File

@ -677,7 +677,6 @@ class PlotItem(GraphicsWidget):
xRange = rect.left(), rect.right() xRange = rect.left(), rect.right()
svg = "" svg = ""
fh = open(fileName, 'w')
dx = max(rect.right(),0) - min(rect.left(),0) dx = max(rect.right(),0) - min(rect.left(),0)
ymn = min(rect.top(), rect.bottom()) ymn = min(rect.top(), rect.bottom())
@ -691,9 +690,18 @@ class PlotItem(GraphicsWidget):
sy *= 1000 sy *= 1000
sy *= -1 sy *= -1
with open(fileName, 'w') as fh:
# fh.write('<svg viewBox="%f %f %f %f">\n' % (rect.left() * sx,
# rect.top() * sx,
# rect.width() * sy,
# rect.height()*sy))
fh.write('<svg>\n') fh.write('<svg>\n')
fh.write('<path fill="none" stroke="#000000" stroke-opacity="0.5" stroke-width="1" d="M%f,0 L%f,0"/>\n' % (rect.left()*sx, rect.right()*sx)) fh.write('<path fill="none" stroke="#000000" stroke-opacity="0.5" '
fh.write('<path fill="none" stroke="#000000" stroke-opacity="0.5" stroke-width="1" d="M0,%f L0,%f"/>\n' % (rect.top()*sy, rect.bottom()*sy)) 'stroke-width="1" d="M%f,0 L%f,0"/>\n' % (
rect.left() * sx, rect.right() * sx))
fh.write('<path fill="none" stroke="#000000" stroke-opacity="0.5" '
'stroke-width="1" d="M0,%f L0,%f"/>\n' % (
rect.top() * sy, rect.bottom() * sy))
for item in self.curves: for item in self.curves:
if isinstance(item, PlotCurveItem): if isinstance(item, PlotCurveItem):
@ -711,15 +719,20 @@ class PlotItem(GraphicsWidget):
x *= sx x *= sx
y *= sy y *= sy
fh.write('<path fill="none" stroke="#%s" stroke-opacity="%f" stroke-width="1" d="M%f,%f ' % (color, opacity, x[0], y[0])) # fh.write('<g fill="none" stroke="#%s" '
# 'stroke-opacity="1" stroke-width="1">\n' % (
# color, ))
fh.write('<path fill="none" stroke="#%s" '
'stroke-opacity="%f" stroke-width="1" '
'd="M%f,%f ' % (color, opacity, x[0], y[0]))
for i in range(1, len(x)): for i in range(1, len(x)):
fh.write('L%f,%f ' % (x[i], y[i])) fh.write('L%f,%f ' % (x[i], y[i]))
fh.write('"/>') fh.write('"/>')
# fh.write("</g>")
for item in self.dataItems: for item in self.dataItems:
if isinstance(item, ScatterPlotItem): if isinstance(item, ScatterPlotItem):
pRect = item.boundingRect() pRect = item.boundingRect()
vRect = pRect.intersected(rect) vRect = pRect.intersected(rect)
@ -733,7 +746,9 @@ class PlotItem(GraphicsWidget):
x = pos.x() * sx x = pos.x() * sx
y = pos.y() * sy y = pos.y() * sy
fh.write('<circle cx="%f" cy="%f" r="1" fill="#%s" stroke="none" fill-opacity="%f"/>\n' % (x, y, color, opacity)) fh.write('<circle cx="%f" cy="%f" r="1" fill="#%s" '
'stroke="none" fill-opacity="%f"/>\n' % (
x, y, color, opacity))
fh.write("</svg>\n") fh.write("</svg>\n")
@ -766,14 +781,14 @@ class PlotItem(GraphicsWidget):
fileName = str(fileName) fileName = str(fileName)
PlotItem.lastFileDir = os.path.dirname(fileName) PlotItem.lastFileDir = os.path.dirname(fileName)
fd = open(fileName, 'w')
data = [c.getData() for c in self.curves] data = [c.getData() for c in self.curves]
with open(fileName, 'w') as fd:
i = 0 i = 0
while True: while True:
done = True done = True
for d in data: for d in data:
if i < len(d[0]): if i < len(d[0]):
fd.write('%g,%g,'%(d[0][i], d[1][i])) fd.write('%g,%g,' % (d[0][i], d[1][i]))
done = False done = False
else: else:
fd.write(' , ,') fd.write(' , ,')
@ -781,7 +796,6 @@ class PlotItem(GraphicsWidget):
if done: if done:
break break
i += 1 i += 1
fd.close()
def saveState(self): def saveState(self):
state = self.stateGroup.state() state = self.stateGroup.state()

View File

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
import weakref import weakref
import sys import sys
from copy import deepcopy from copy import deepcopy
import numpy as np import numpy as np
from ...Qt import QtGui, QtCore from ...Qt import QtGui, QtCore
from ...python2_3 import sortList, basestring, cmp from ...python2_3 import basestring
from ...Point import Point from ...Point import Point
from ... import functions as fn from ... import functions as fn
from .. ItemGroup import ItemGroup from .. ItemGroup import ItemGroup
@ -1604,14 +1605,11 @@ class ViewBox(GraphicsWidget):
except RuntimeError: ## this view has already been deleted; it will probably be collected shortly. except RuntimeError: ## this view has already been deleted; it will probably be collected shortly.
return return
def cmpViews(a, b): def view_key(view):
wins = 100 * cmp(a.window() is self.window(), b.window() is self.window()) return (view.window() is self.window(), view.name)
alpha = cmp(a.name, b.name)
return wins + alpha
## make a sorted list of all named views ## make a sorted list of all named views
nv = list(ViewBox.NamedViews.values()) nv = sorted(ViewBox.NamedViews.values(), key=view_key)
sortList(nv, cmpViews) ## see pyqtgraph.python2_3.sortList
if self in nv: if self in nv:
nv.remove(self) nv.remove(self)

View File

@ -12,7 +12,6 @@ More info at http://www.scipy.org/Cookbook/MetaArray
import types, copy, threading, os, re import types, copy, threading, os, re
import pickle import pickle
from functools import reduce
import numpy as np import numpy as np
from ..python2_3 import basestring from ..python2_3 import basestring
#import traceback #import traceback
@ -844,7 +843,7 @@ class MetaArray(object):
frames = [] frames = []
frameShape = list(meta['shape']) frameShape = list(meta['shape'])
frameShape[dynAxis] = 1 frameShape[dynAxis] = 1
frameSize = reduce(lambda a,b: a*b, frameShape) frameSize = np.prod(frameShape)
n = 0 n = 0
while True: while True:
## Extract one non-blank line ## Extract one non-blank line
@ -1298,7 +1297,7 @@ class MetaArray(object):
#frames = [] #frames = []
#frameShape = list(meta['shape']) #frameShape = list(meta['shape'])
#frameShape[dynAxis] = 1 #frameShape[dynAxis] = 1
#frameSize = reduce(lambda a,b: a*b, frameShape) #frameSize = np.prod(frameShape)
#n = 0 #n = 0
#while True: #while True:
### Extract one non-blank line ### Extract one non-blank line

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
import os, sys, time, multiprocessing, re import os, sys, time, multiprocessing, re
from .processes import ForkedProcess from .processes import ForkedProcess
from .remoteproxy import ClosedError from .remoteproxy import ClosedError
@ -213,8 +214,8 @@ class Parallelize(object):
try: try:
cores = {} cores = {}
pid = None pid = None
with open('/proc/cpuinfo') as fd:
for line in open('/proc/cpuinfo'): for line in fd:
m = re.match(r'physical id\s+:\s+(\d+)', line) m = re.match(r'physical id\s+:\s+(\d+)', line)
if m is not None: if m is not None:
pid = m.groups()[0] pid = m.groups()[0]

View File

@ -123,7 +123,7 @@ class GLScatterPlotItem(GLGraphicsItem):
try: try:
pos = self.pos pos = self.pos
#if pos.ndim > 2: #if pos.ndim > 2:
#pos = pos.reshape((reduce(lambda a,b: a*b, pos.shape[:-1]), pos.shape[-1])) #pos = pos.reshape((-1, pos.shape[-1]))
glVertexPointerf(pos) glVertexPointerf(pos)
if isinstance(self.color, np.ndarray): if isinstance(self.color, np.ndarray):

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
import numpy as np import numpy as np
from PyQt4 import QtGui from PyQt4 import QtGui
import os, pickle, sys import os, pickle, sys
@ -14,6 +15,5 @@ for f in os.listdir(path):
arr = np.asarray(ptr).reshape(img.height(), img.width(), 4).transpose(1,0,2) arr = np.asarray(ptr).reshape(img.height(), img.width(), 4).transpose(1,0,2)
pixmaps[f] = pickle.dumps(arr) pixmaps[f] = pickle.dumps(arr)
ver = sys.version_info[0] ver = sys.version_info[0]
fh = open(os.path.join(path, 'pixmapData_%d.py' %ver), 'w') with open(os.path.join(path, 'pixmapData_%d.py' % (ver, )), 'w') as fh:
fh.write("import numpy as np; pixmapData=%s" % repr(pixmaps)) fh.write("import numpy as np; pixmapData=%s" % (repr(pixmaps), ))

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
""" """
Helper functions that smooth out the differences between python 2 and 3. Helper functions that smooth out the differences between python 2 and 3.
""" """
@ -14,45 +15,11 @@ def asUnicode(x):
else: else:
return str(x) return str(x)
def cmpToKey(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K
def sortList(l, cmpFunc):
if sys.version_info[0] == 2:
l.sort(cmpFunc)
else:
l.sort(key=cmpToKey(cmpFunc))
if sys.version_info[0] == 3: if sys.version_info[0] == 3:
basestring = str basestring = str
def cmp(a,b):
if a>b:
return 1
elif b > a:
return -1
else:
return 0
xrange = range xrange = range
else: else:
import __builtin__ import __builtin__
basestring = __builtin__.basestring basestring = __builtin__.basestring
cmp = __builtin__.cmp
xrange = __builtin__.xrange xrange = __builtin__.xrange

View File

@ -306,7 +306,8 @@ if __name__ == '__main__':
import os import os
if not os.path.isdir('test1'): if not os.path.isdir('test1'):
os.mkdir('test1') os.mkdir('test1')
open('test1/__init__.py', 'w') with open('test1/__init__.py', 'w'):
pass
modFile1 = "test1/test1.py" modFile1 = "test1/test1.py"
modCode1 = """ modCode1 = """
import sys import sys
@ -345,8 +346,10 @@ def fn():
print("fn: %s") print("fn: %s")
""" """
open(modFile1, 'w').write(modCode1%(1,1)) with open(modFile1, 'w') as f:
open(modFile2, 'w').write(modCode2%"message 1") f.write(modCode1 % (1, 1))
with open(modFile2, 'w') as f:
f.write(modCode2 % ("message 1", ))
import test1.test1 as test1 import test1.test1 as test1
import test2 import test2
print("Test 1 originals:") print("Test 1 originals:")
@ -382,7 +385,8 @@ def fn():
c1.fn() c1.fn()
os.remove(modFile1+'c') os.remove(modFile1+'c')
open(modFile1, 'w').write(modCode1%(2,2)) with open(modFile1, 'w') as f:
f.write(modCode1 %(2, 2))
print("\n----RELOAD test1-----\n") print("\n----RELOAD test1-----\n")
reloadAll(os.path.abspath(__file__)[:10], debug=True) reloadAll(os.path.abspath(__file__)[:10], debug=True)
@ -393,7 +397,8 @@ def fn():
os.remove(modFile2+'c') os.remove(modFile2+'c')
open(modFile2, 'w').write(modCode2%"message 2") with open(modFile2, 'w') as f:
f.write(modCode2 % ("message 2", ))
print("\n----RELOAD test2-----\n") print("\n----RELOAD test2-----\n")
reloadAll(os.path.abspath(__file__)[:10], debug=True) reloadAll(os.path.abspath(__file__)[:10], debug=True)
@ -429,8 +434,10 @@ def fn():
os.remove(modFile1+'c') os.remove(modFile1+'c')
os.remove(modFile2+'c') os.remove(modFile2+'c')
open(modFile1, 'w').write(modCode1%(3,3)) with open(modFile1, 'w') as f:
open(modFile2, 'w').write(modCode2%"message 3") f.write(modCode1 % (3, 3))
with open(modFile2, 'w') as f:
f.write(modCode2 % ("message 3", ))
print("\n----RELOAD-----\n") print("\n----RELOAD-----\n")
reloadAll(os.path.abspath(__file__)[:10], debug=True) reloadAll(os.path.abspath(__file__)[:10], debug=True)

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
import os import os
import sys import sys
import subprocess import subprocess
@ -59,7 +60,8 @@ def test_exit_crash():
print(name) print(name)
argstr = initArgs.get(name, "") argstr = initArgs.get(name, "")
open(tmp, 'w').write(code.format(path=path, classname=name, args=argstr)) with open(tmp, 'w') as f:
f.write(code.format(path=path, classname=name, args=argstr))
proc = subprocess.Popen([sys.executable, tmp]) proc = subprocess.Popen([sys.executable, tmp])
assert proc.wait() == 0 assert proc.wait() == 0

View File

@ -355,7 +355,8 @@ class TableWidget(QtGui.QTableWidget):
fileName = fileName[0] # Qt4/5 API difference fileName = fileName[0] # Qt4/5 API difference
if fileName == '': if fileName == '':
return return
open(str(fileName), 'w').write(data) with open(fileName, 'w') as fd:
fd.write(data)
def contextMenuEvent(self, ev): def contextMenuEvent(self, ev):
self.contextMenu.popup(ev.globalPos()) self.contextMenu.popup(ev.globalPos())

View File

@ -1,7 +1,6 @@
from ..Qt import QtCore, QtGui from ..Qt import QtCore, QtGui
from ..ptime import time from ..ptime import time
from .. import functions as fn from .. import functions as fn
from functools import reduce
__all__ = ['ValueLabel'] __all__ = ['ValueLabel']
@ -54,7 +53,7 @@ class ValueLabel(QtGui.QLabel):
self.averageTime = t self.averageTime = t
def averageValue(self): def averageValue(self):
return reduce(lambda a,b: a+b, [v[1] for v in self.values]) / float(len(self.values)) return sum(v[1] for v in self.values) / float(len(self.values))
def paintEvent(self, ev): def paintEvent(self, ev):