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
from ..Qt import QtCore, QtGui
from ..python2_3 import sortList, cmp
from ..Point import Point
from .. import functions as fn
from .. import ptime as ptime
@ -454,7 +454,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
return 0
return item.zValue() + absZValue(item.parentItem())
sortList(items2, lambda a,b: cmp(absZValue(b), absZValue(a)))
items2.sort(key=absZValue, reverse=True)
return items2
@ -563,6 +563,3 @@ class GraphicsScene(QtGui.QGraphicsScene):
@staticmethod
def translateGraphicsItems(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
lastRevFile = os.path.join(os.path.dirname(__file__), '..', '.bzr', 'branch', 'last-revision')
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("config:")

View File

@ -1,8 +1,4 @@
# -*- 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 ..graphicsItems.ROI import ROI

View File

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

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
import sys, re, os, time, traceback, subprocess
import pickle
@ -98,12 +99,14 @@ class ConsoleWidget(QtGui.QWidget):
def loadHistory(self):
"""Return the list of previously-invoked command strings (or 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):
"""Store the list of previously-invoked command strings."""
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):
self.stdout = sys.stdout

View File

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

View File

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

View File

@ -677,7 +677,6 @@ class PlotItem(GraphicsWidget):
xRange = rect.left(), rect.right()
svg = ""
fh = open(fileName, 'w')
dx = max(rect.right(),0) - min(rect.left(),0)
ymn = min(rect.top(), rect.bottom())
@ -691,52 +690,68 @@ class PlotItem(GraphicsWidget):
sy *= 1000
sy *= -1
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" stroke-width="1" d="M0,%f L0,%f"/>\n' % (rect.top()*sy, rect.bottom()*sy))
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('<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" '
'stroke-width="1" d="M0,%f L0,%f"/>\n' % (
rect.top() * sy, rect.bottom() * sy))
for item in self.curves:
if isinstance(item, PlotCurveItem):
color = fn.colorStr(item.pen.color())
opacity = item.pen.color().alpha() / 255.
color = color[:6]
x, y = item.getData()
mask = (x > xRange[0]) * (x < xRange[1])
mask[:-1] += mask[1:]
m2 = mask.copy()
mask[1:] += m2[:-1]
x = x[mask]
y = y[mask]
x *= sx
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]))
for i in range(1, len(x)):
fh.write('L%f,%f ' % (x[i], y[i]))
fh.write('"/>')
for item in self.dataItems:
if isinstance(item, ScatterPlotItem):
pRect = item.boundingRect()
vRect = pRect.intersected(rect)
for point in item.points():
pos = point.pos()
if not rect.contains(pos):
continue
color = fn.colorStr(point.brush.color())
opacity = point.brush.color().alpha() / 255.
for item in self.curves:
if isinstance(item, PlotCurveItem):
color = fn.colorStr(item.pen.color())
opacity = item.pen.color().alpha() / 255.
color = color[:6]
x = pos.x() * sx
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("</svg>\n")
x, y = item.getData()
mask = (x > xRange[0]) * (x < xRange[1])
mask[:-1] += mask[1:]
m2 = mask.copy()
mask[1:] += m2[:-1]
x = x[mask]
y = y[mask]
x *= sx
y *= sy
# 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)):
fh.write('L%f,%f ' % (x[i], y[i]))
fh.write('"/>')
# fh.write("</g>")
for item in self.dataItems:
if isinstance(item, ScatterPlotItem):
pRect = item.boundingRect()
vRect = pRect.intersected(rect)
for point in item.points():
pos = point.pos()
if not rect.contains(pos):
continue
color = fn.colorStr(point.brush.color())
opacity = point.brush.color().alpha() / 255.
color = color[:6]
x = pos.x() * sx
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("</svg>\n")
def writeSvg(self, fileName=None):
if fileName is None:
self._chooseFilenameDialog(handler=self.writeSvg)
@ -766,22 +781,21 @@ class PlotItem(GraphicsWidget):
fileName = str(fileName)
PlotItem.lastFileDir = os.path.dirname(fileName)
fd = open(fileName, 'w')
data = [c.getData() for c in self.curves]
i = 0
while True:
done = True
for d in data:
if i < len(d[0]):
fd.write('%g,%g,'%(d[0][i], d[1][i]))
done = False
else:
fd.write(' , ,')
fd.write('\n')
if done:
break
i += 1
fd.close()
with open(fileName, 'w') as fd:
i = 0
while True:
done = True
for d in data:
if i < len(d[0]):
fd.write('%g,%g,' % (d[0][i], d[1][i]))
done = False
else:
fd.write(' , ,')
fd.write('\n')
if done:
break
i += 1
def saveState(self):
state = self.stateGroup.state()

View File

@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
import weakref
import sys
from copy import deepcopy
import numpy as np
from ...Qt import QtGui, QtCore
from ...python2_3 import sortList, basestring, cmp
from ...python2_3 import basestring
from ...Point import Point
from ... import functions as fn
from .. ItemGroup import ItemGroup
@ -1603,16 +1604,13 @@ class ViewBox(GraphicsWidget):
self.window()
except RuntimeError: ## this view has already been deleted; it will probably be collected shortly.
return
def cmpViews(a, b):
wins = 100 * cmp(a.window() is self.window(), b.window() is self.window())
alpha = cmp(a.name, b.name)
return wins + alpha
def view_key(view):
return (view.window() is self.window(), view.name)
## make a sorted list of all named views
nv = list(ViewBox.NamedViews.values())
sortList(nv, cmpViews) ## see pyqtgraph.python2_3.sortList
nv = sorted(ViewBox.NamedViews.values(), key=view_key)
if self in nv:
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 pickle
from functools import reduce
import numpy as np
from ..python2_3 import basestring
#import traceback
@ -844,7 +843,7 @@ class MetaArray(object):
frames = []
frameShape = list(meta['shape'])
frameShape[dynAxis] = 1
frameSize = reduce(lambda a,b: a*b, frameShape)
frameSize = np.prod(frameShape)
n = 0
while True:
## Extract one non-blank line
@ -1298,7 +1297,7 @@ class MetaArray(object):
#frames = []
#frameShape = list(meta['shape'])
#frameShape[dynAxis] = 1
#frameSize = reduce(lambda a,b: a*b, frameShape)
#frameSize = np.prod(frameShape)
#n = 0
#while True:
### Extract one non-blank line

View File

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

View File

@ -123,7 +123,7 @@ class GLScatterPlotItem(GLGraphicsItem):
try:
pos = self.pos
#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)
if isinstance(self.color, np.ndarray):

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
import numpy as np
from PyQt4 import QtGui
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)
pixmaps[f] = pickle.dumps(arr)
ver = sys.version_info[0]
fh = open(os.path.join(path, 'pixmapData_%d.py' %ver), 'w')
fh.write("import numpy as np; pixmapData=%s" % repr(pixmaps))
with open(os.path.join(path, 'pixmapData_%d.py' % (ver, )), 'w') as fh:
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.
"""
@ -13,46 +14,12 @@ def asUnicode(x):
return unicode(x)
else:
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:
basestring = str
def cmp(a,b):
if a>b:
return 1
elif b > a:
return -1
else:
return 0
xrange = range
else:
import __builtin__
basestring = __builtin__.basestring
cmp = __builtin__.cmp
xrange = __builtin__.xrange

View File

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

View File

@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
@ -59,7 +60,8 @@ def test_exit_crash():
print(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])
assert proc.wait() == 0

View File

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

View File

@ -1,7 +1,6 @@
from ..Qt import QtCore, QtGui
from ..ptime import time
from .. import functions as fn
from functools import reduce
__all__ = ['ValueLabel']
@ -54,7 +53,7 @@ class ValueLabel(QtGui.QLabel):
self.averageTime = t
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):