Fixed print statements for python 3

This commit is contained in:
Luke Campagnola 2013-01-12 14:35:32 -05:00
parent 9a9fc15873
commit c5dd0f4f63
12 changed files with 55 additions and 54 deletions

View File

@ -68,6 +68,7 @@ examples = OrderedDict([
('GraphicsScene', 'GraphicsScene.py'), ('GraphicsScene', 'GraphicsScene.py'),
('Flowcharts', 'Flowchart.py'), ('Flowcharts', 'Flowchart.py'),
('Custom Flowchart Nodes', 'FlowchartCustomNode.py'),
#('Canvas', '../canvas'), #('Canvas', '../canvas'),
#('MultiPlotWidget', 'MultiPlotWidget.py'), #('MultiPlotWidget', 'MultiPlotWidget.py'),
]) ])

View File

@ -8,32 +8,32 @@ import time
print "\n=================\nStart Process" print("\n=================\nStart Process")
proc = mp.Process() proc = mp.Process()
import os import os
print "parent:", os.getpid(), "child:", proc.proc.pid print("parent:", os.getpid(), "child:", proc.proc.pid)
print "started" print("started")
rnp = proc._import('numpy') rnp = proc._import('numpy')
arr = rnp.array([1,2,3,4]) arr = rnp.array([1,2,3,4])
print repr(arr) print(repr(arr))
print str(arr) print(str(arr))
print "return value:", repr(arr.mean(_returnType='value')) print("return value:", repr(arr.mean(_returnType='value')))
print "return proxy:", repr(arr.mean(_returnType='proxy')) print( "return proxy:", repr(arr.mean(_returnType='proxy')))
print "return auto: ", repr(arr.mean(_returnType='auto')) print( "return auto: ", repr(arr.mean(_returnType='auto')))
proc.join() proc.join()
print "process finished" print( "process finished")
print "\n=================\nStart ForkedProcess" print( "\n=================\nStart ForkedProcess")
proc = mp.ForkedProcess() proc = mp.ForkedProcess()
rnp = proc._import('numpy') rnp = proc._import('numpy')
arr = rnp.array([1,2,3,4]) arr = rnp.array([1,2,3,4])
print repr(arr) print( repr(arr))
print str(arr) print( str(arr))
print repr(arr.mean()) print( repr(arr.mean()))
proc.join() proc.join()
print "process finished" print( "process finished")
@ -42,10 +42,10 @@ import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui from pyqtgraph.Qt import QtCore, QtGui
app = pg.QtGui.QApplication([]) app = pg.QtGui.QApplication([])
print "\n=================\nStart QtProcess" print( "\n=================\nStart QtProcess")
import sys import sys
if (sys.flags.interactive != 1): if (sys.flags.interactive != 1):
print " (not interactive; remote process will exit immediately.)" print( " (not interactive; remote process will exit immediately.)")
proc = mp.QtProcess() proc = mp.QtProcess()
d1 = proc.transfer(np.random.normal(size=1000)) d1 = proc.transfer(np.random.normal(size=1000))
d2 = proc.transfer(np.random.normal(size=1000)) d2 = proc.transfer(np.random.normal(size=1000))

View File

@ -5,7 +5,7 @@ import pyqtgraph.multiprocess as mp
import pyqtgraph as pg import pyqtgraph as pg
import time import time
print "\n=================\nParallelize" print( "\n=================\nParallelize")
## Do a simple task: ## Do a simple task:
## for x in range(N): ## for x in range(N):
@ -36,7 +36,7 @@ with pg.ProgressDialog('processing serially..', maximum=len(tasks)) as dlg:
dlg += 1 dlg += 1
if dlg.wasCanceled(): if dlg.wasCanceled():
raise Exception('processing canceled') raise Exception('processing canceled')
print "Serial time: %0.2f" % (time.time() - start) print( "Serial time: %0.2f" % (time.time() - start))
### Use parallelize, but force a single worker ### Use parallelize, but force a single worker
### (this simulates the behavior seen on windows, which lacks os.fork) ### (this simulates the behavior seen on windows, which lacks os.fork)
@ -47,8 +47,8 @@ with mp.Parallelize(enumerate(tasks), results=results2, workers=1, progressDialo
for j in xrange(size): for j in xrange(size):
tot += j * x tot += j * x
tasker.results[i] = tot tasker.results[i] = tot
print "\nParallel time, 1 worker: %0.2f" % (time.time() - start) print( "\nParallel time, 1 worker: %0.2f" % (time.time() - start))
print "Results match serial: ", results2 == results print( "Results match serial: %s" % str(results2 == results))
### Use parallelize with multiple workers ### Use parallelize with multiple workers
start = time.time() start = time.time()
@ -58,6 +58,6 @@ with mp.Parallelize(enumerate(tasks), results=results3, progressDialog='processi
for j in xrange(size): for j in xrange(size):
tot += j * x tot += j * x
tasker.results[i] = tot tasker.results[i] = tot
print "\nParallel time, %d workers: %0.2f" % (mp.Parallelize.suggestedWorkerCount(), time.time() - start) print( "\nParallel time, %d workers: %0.2f" % (mp.Parallelize.suggestedWorkerCount(), time.time() - start))
print "Results match serial: ", results3 == results print( "Results match serial: %s" % str(results3 == results))

View File

@ -393,7 +393,7 @@ class Profiler:
if self.delayed: if self.delayed:
self.msgs.append(msg2) self.msgs.append(msg2)
else: else:
print msg2 print(msg2)
self.t0 = ptime.time() self.t0 = ptime.time()
self.t1 = self.t0 self.t1 = self.t0
@ -410,7 +410,7 @@ class Profiler:
if self.delayed: if self.delayed:
self.msgs.append(msg2) self.msgs.append(msg2)
else: else:
print msg2 print(msg2)
self.t1 = ptime.time() ## don't measure time it took to print self.t1 = ptime.time() ## don't measure time it took to print
def finish(self, msg=None): def finish(self, msg=None):
@ -425,10 +425,10 @@ class Profiler:
self.msgs.append(msg) self.msgs.append(msg)
if self.depth == 0: if self.depth == 0:
for line in self.msgs: for line in self.msgs:
print line print(line)
Profiler.msgs = [] Profiler.msgs = []
else: else:
print msg print(msg)
Profiler.depth = self.depth Profiler.depth = self.depth
self.finished = True self.finished = True

View File

@ -220,7 +220,7 @@ def _generateItemSvg(item, nodes=None, root=None):
## get list of sub-groups ## get list of sub-groups
g2 = [n for n in g1.childNodes if isinstance(n, xml.Element) and n.tagName == 'g'] g2 = [n for n in g1.childNodes if isinstance(n, xml.Element) and n.tagName == 'g']
except: except:
print doc.toxml() print(doc.toxml())
raise raise

View File

@ -236,7 +236,7 @@ class EvalNode(Node):
text = fn + "\n".join([" "+l for l in str(self.text.toPlainText()).split('\n')]) + run text = fn + "\n".join([" "+l for l in str(self.text.toPlainText()).split('\n')]) + run
exec(text) exec(text)
except: except:
print "Error processing node:", self.name() print("Error processing node: %s" % self.name())
raise raise
return output return output

View File

@ -798,7 +798,7 @@ def makeARGB(data, lut=None, levels=None, scale=None, useRGBA=False):
if levels.shape != (data.shape[-1], 2): if levels.shape != (data.shape[-1], 2):
raise Exception('levels must have shape (data.shape[-1], 2)') raise Exception('levels must have shape (data.shape[-1], 2)')
else: else:
print levels print(levels)
raise Exception("levels argument must be 1D or 2D.") raise Exception("levels argument must be 1D or 2D.")
#levels = np.array(levels) #levels = np.array(levels)
#if levels.shape == (2,): #if levels.shape == (2,):

View File

@ -19,7 +19,7 @@ class Parallelize(object):
for task in tasks: for task in tasks:
result = processTask(task) result = processTask(task)
results.append(result) results.append(result)
print results print(results)
## Here is the parallelized version: ## Here is the parallelized version:
@ -30,7 +30,7 @@ class Parallelize(object):
for task in tasker: for task in tasker:
result = processTask(task) result = processTask(task)
tasker.results.append(result) tasker.results.append(result)
print results print(results)
The only major caveat is that *result* in the example above must be picklable, The only major caveat is that *result* in the example above must be picklable,

View File

@ -232,7 +232,7 @@ class ForkedProcess(RemoteEventHandler):
except ClosedError: except ClosedError:
break break
except: except:
print "Error occurred in forked event loop:" print("Error occurred in forked event loop:")
sys.excepthook(*sys.exc_info()) sys.excepthook(*sys.exc_info())
sys.exit(0) sys.exit(0)
@ -297,7 +297,7 @@ class QtProcess(Process):
btn.show() btn.show()
def slot(): def slot():
print 'slot invoked on parent process' print('slot invoked on parent process')
btn.clicked.connect(proxy(slot)) # be sure to send a proxy of the slot btn.clicked.connect(proxy(slot)) # be sure to send a proxy of the slot
""" """

View File

@ -68,7 +68,7 @@ class RemoteEventHandler(object):
try: try:
return cls.handlers[pid] return cls.handlers[pid]
except: except:
print pid, cls.handlers print(pid, cls.handlers)
raise raise
def getProxyOption(self, opt): def getProxyOption(self, opt):
@ -103,7 +103,7 @@ class RemoteEventHandler(object):
else: else:
raise raise
except: except:
print "Error in process %s" % self.name print("Error in process %s" % self.name)
sys.excepthook(*sys.exc_info()) sys.excepthook(*sys.exc_info())
return numProcessed return numProcessed
@ -239,7 +239,7 @@ class RemoteEventHandler(object):
self.send(request='result', reqId=reqId, callSync='off', opts=dict(result=result)) self.send(request='result', reqId=reqId, callSync='off', opts=dict(result=result))
def replyError(self, reqId, *exc): def replyError(self, reqId, *exc):
print "error:", self.name, reqId, exc[1] print("error: %s %s %s" % (self.name, str(reqId), str(exc[1])))
excStr = traceback.format_exception(*exc) excStr = traceback.format_exception(*exc)
try: try:
self.send(request='error', reqId=reqId, callSync='off', opts=dict(exception=exc[1], excString=excStr)) self.send(request='error', reqId=reqId, callSync='off', opts=dict(exception=exc[1], excString=excStr))
@ -352,9 +352,9 @@ class RemoteEventHandler(object):
try: try:
optStr = pickle.dumps(opts) optStr = pickle.dumps(opts)
except: except:
print "==== Error pickling this object: ====" print("==== Error pickling this object: ====")
print opts print(opts)
print "=======================================" print("=======================================")
raise raise
nByteMsgs = 0 nByteMsgs = 0
@ -404,12 +404,12 @@ class RemoteEventHandler(object):
#print ''.join(result) #print ''.join(result)
exc, excStr = result exc, excStr = result
if exc is not None: if exc is not None:
print "===== Remote process raised exception on request: =====" print("===== Remote process raised exception on request: =====")
print ''.join(excStr) print(''.join(excStr))
print "===== Local Traceback to request follows: =====" print("===== Local Traceback to request follows: =====")
raise exc raise exc
else: else:
print ''.join(excStr) print(''.join(excStr))
raise Exception("Error getting result. See above for exception from remote process.") raise Exception("Error getting result. See above for exception from remote process.")
else: else:
@ -535,7 +535,7 @@ class Request(object):
raise ClosedError() raise ClosedError()
time.sleep(0.005) time.sleep(0.005)
if timeout >= 0 and time.time() - start > timeout: if timeout >= 0 and time.time() - start > timeout:
print "Request timed out:", self.description print("Request timed out: %s" % self.description)
import traceback import traceback
traceback.print_stack() traceback.print_stack()
raise NoResultError() raise NoResultError()

View File

@ -6,10 +6,10 @@ class GLTest(QtOpenGL.QGLWidget):
def __init__(self): def __init__(self):
QtOpenGL.QGLWidget.__init__(self) QtOpenGL.QGLWidget.__init__(self)
self.makeCurrent() self.makeCurrent()
print "GL version:", glGetString(GL_VERSION) print("GL version:" + glGetString(GL_VERSION))
print "MAX_TEXTURE_SIZE:", glGetIntegerv(GL_MAX_TEXTURE_SIZE) print("MAX_TEXTURE_SIZE: %d" % glGetIntegerv(GL_MAX_TEXTURE_SIZE))
print "MAX_3D_TEXTURE_SIZE:", glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE) print("MAX_3D_TEXTURE_SIZE: %d" % glGetIntegerv(GL_MAX_3D_TEXTURE_SIZE))
print "Extensions:", glGetString(GL_EXTENSIONS) print("Extensions: " + glGetString(GL_EXTENSIONS))
GLTest() GLTest()

View File

@ -267,14 +267,14 @@ class A(object):
object.__init__(self) object.__init__(self)
self.msg = msg self.msg = msg
def fn(self, pfx = ""): def fn(self, pfx = ""):
print pfx+"A class:", self.__class__, id(self.__class__) print(pfx+"A class: %%s %%s" %% (str(self.__class__), str(id(self.__class__))))
print pfx+" %%s: %d" %% self.msg print(pfx+" %%s: %d" %% self.msg)
class B(A): class B(A):
def fn(self, pfx=""): def fn(self, pfx=""):
print pfx+"B class:", self.__class__, id(self.__class__) print(pfx+"B class:", self.__class__, id(self.__class__))
print pfx+" %%s: %d" %% self.msg print(pfx+" %%s: %d" %% self.msg)
print pfx+" calling superclass.. (%%s)" %% id(A) print(pfx+" calling superclass.. (%%s)" %% id(A) )
A.fn(self, " ") A.fn(self, " ")
""" """
@ -294,7 +294,7 @@ class C(A):
A.__init__(self, msg + "(init from C)") A.__init__(self, msg + "(init from C)")
def fn(): def fn():
print "fn: %s" print("fn: %s")
""" """
open(modFile1, 'w').write(modCode1%(1,1)) open(modFile1, 'w').write(modCode1%(1,1))