From: W. Trevor King Date: Mon, 19 Nov 2012 11:48:52 +0000 (-0500) Subject: Convert from "print ..." to "print(...)" X-Git-Url: http://git.tremily.us/?a=commitdiff_plain;h=60b12a779acf92ec32ef2d0ed9e5766b11705150;p=hooke.git Convert from "print ..." to "print(...)" Also convert "'...' % (...)" to "'...'.format(...)". These bring us up to date with Python 2.7, and will make future porting to Python 3 less painful. --- diff --git a/contrib/mfp_igor_scripts/FMjoin.py b/contrib/mfp_igor_scripts/FMjoin.py index 73a9ec5..615a957 100644 --- a/contrib/mfp_igor_scripts/FMjoin.py +++ b/contrib/mfp_igor_scripts/FMjoin.py @@ -30,7 +30,8 @@ import sys def main(*args): if len(sys.argv) < 2: - print 'You must at least specify origin and destination folders.' + print('You must at least specify origin and destination ' + 'folders.') return 0 origin=sys.argv[1] dest=sys.argv[2] @@ -38,13 +39,15 @@ def main(*args): if os.path.exists(origin): if os.path.exists(dest): if os.listdir(dest)!=[]: - print 'Destination folder is not empty! Use another folder.' + print('Destination folder is not empty! Use ' + 'another folder.') return 0 else: - print 'Destination folder does not exist, will create it' + print('Destination folder does not exist, will create ' + 'it') os.mkdir(dest) else: - print 'You provided a wrong origin folder name, try again.' + print('You provided a wrong origin folder name, try again.') origin=os.path.abspath(origin) dest=os.path.abspath(dest) @@ -59,7 +62,7 @@ def main(*args): rawdest=rawdest.replace('/','') #for linux rawdest=rawdest.replace('\\','') #for windows destfile=os.path.join(dest,rawdest) - print 'Copying '+rawdest + print('Copying '+rawdest) shutil.copy(filepath,destfile) return 0 diff --git a/contrib/mfp_igor_scripts/h5export.py b/contrib/mfp_igor_scripts/h5export.py index 2ee7d6f..0cd7893 100644 --- a/contrib/mfp_igor_scripts/h5export.py +++ b/contrib/mfp_igor_scripts/h5export.py @@ -30,7 +30,7 @@ exportdir=os.path.join(h5dir,'exported') try: os.mkdir(exportdir) except: - print 'mkdir error, maybe the export directory already exists?' + print('mkdir error, maybe the export directory already exists?') def h5exportfunc(name): Deflname=name @@ -43,9 +43,10 @@ def h5exportfunc(name): notes=f[Deflname].attrs['IGORWaveNote'] springmatch=notes.index("SpringConstant: ")+len("SpringConstant: ") springc=notes[springmatch:].split("\r",1)[0] #probably extracting the leading numbers can be way more elegant than this - print Deflname + print(Deflname) except: - print 'Something bad happened with '+Deflname+', ignoring it' + print('Something bad happened with '+Deflname+ + ', ignoring it') return None #returning anything but None halts the visit procedure diff --git a/contrib/upgrade_playlist_0p1.py b/contrib/upgrade_playlist_0p1.py index 0e6988c..c373f64 100755 --- a/contrib/upgrade_playlist_0p1.py +++ b/contrib/upgrade_playlist_0p1.py @@ -77,7 +77,7 @@ class Converter (FilePlaylist): >>> p.info {u'note': u'An example playlist'} >>> for curve in p: - ... print curve.path + ... print(curve.path) path/to/curve/one path/to/curve/two >>> p[-1].info['attr with spaces'] @@ -99,7 +99,7 @@ class Converter (FilePlaylist): if __name__ == '__main__': if len(sys.argv) < 2: - print >> sys.stderr, 'usage: upgrade_playlist_0p1.py X.hkp [Y.hkp ...]' + sys.stderr.write('usage: upgrade_playlist_0p1.py X.hkp [Y.hkp ...]\n') sys.exit(1) for path in sys.argv[1:]: diff --git a/doc/SConstruct b/doc/SConstruct index b416976..a06f315 100644 --- a/doc/SConstruct +++ b/doc/SConstruct @@ -130,8 +130,8 @@ pkgtype = env["pkgtype"] # Dump internals if debugging. if debug: - print "Environment:" - print env.Dump() + print('Environment:') + print(env.Dump()) # Get parameters from Sphinx config file. sphinxparams = {} @@ -160,9 +160,9 @@ help_format = " %-10s %s\n" # Print banner if required. if not any(map(GetOption, ("silent", "clean", "help"))): - print - print "This is", description - print + print('') + print('This is {}'.format(description)) + print('') # Build sphinx command-line options. opts = [] diff --git a/doc/generate-hooke-txt.py b/doc/generate-hooke-txt.py old mode 100644 new mode 100755 index 29dadbe..274afe4 --- a/doc/generate-hooke-txt.py +++ b/doc/generate-hooke-txt.py @@ -121,7 +121,7 @@ class Tree(list): Serialize the tree with depth marking branches. >>> for depth,node in a.thread(): - ... print "%*s" % (2*depth+1, node.n) + ... print('{}{}'.format(' '*2*depth, node.n)) a b d @@ -136,7 +136,7 @@ class Tree(list): branch splits. >>> for depth,node in a.thread(flatten=True): - ... print "%*s" % (2*depth+1, node.n) + ... print('{}{}'.format(' '*2*depth, node.n)) a b d @@ -333,5 +333,5 @@ def python_tree(root_path='hooke', root_modname='hooke'): if __name__ == '__main__': pt = python_tree(root_path='../hooke', root_modname='hooke') for node in pt.traverse(): - print node.modname + print(node.modname) make_module_txt(node.modname, [c.modname for c in node]) diff --git a/hooke/command.py b/hooke/command.py index 49fff93..be5a677 100644 --- a/hooke/command.py +++ b/hooke/command.py @@ -291,4 +291,4 @@ class PrintQueue (NullQueue): def put(self, item, block=True, timeout=None): """Print `item` and then dump it into the void. """ - print 'ITEM:\n%s' % item + print('ITEM:\n{}'.format(item)) diff --git a/hooke/command_stack.py b/hooke/command_stack.py index d9817be..1307a01 100644 --- a/hooke/command_stack.py +++ b/hooke/command_stack.py @@ -51,7 +51,7 @@ class CommandStack (list): >>> def execute_cmd(hooke, command_message, stack=None): ... cm = command_message - ... print 'EXECUTE', cm.command, cm.arguments + ... print('EXECUTE {} {}'.format(cm.command, cm.arguments)) >>> c.execute_command = execute_cmd >>> c.execute(hooke=None) # doctest: +ELLIPSIS @@ -81,7 +81,7 @@ class CommandStack (list): >>> c.execute_command(hooke=None, command_message=cm) EXECUTE CommandC {'param': 'E'} >>> c.append(cm) - >>> print [repr(cm) for cm in c] # doctest: +NORMALIZE_WHITESPACE + >>> print([repr(cm) for cm in c]) # doctest: +NORMALIZE_WHITESPACE ['', '', '', @@ -113,8 +113,8 @@ class CommandStack (list): >>> import pickle >>> s = pickle.dumps(c) >>> z = pickle.loads(s) - >>> print '\\n'.join([repr(cm) for cm in c] - ... ) # doctest: +NORMALIZE_WHITESPACE, + >>> print('\\n'.join([repr(cm) for cm in c])) + ... # doctest: +NORMALIZE_WHITESPACE @@ -127,7 +127,7 @@ class CommandStack (list): , ]}> >>> import yaml - >>> print yaml.dump(c) # doctest: +REPORT_UDIFF + >>> print(yaml.dump(c)) # doctest: +REPORT_UDIFF !!python/object/new:hooke.command_stack.CommandStack listitems: - !!python/object:hooke.engine.CommandMessage @@ -181,14 +181,14 @@ class CommandStack (list): There is also a convenience function for clearing the stack. >>> c.clear() - >>> print [repr(cm) for cm in c] + >>> print([repr(cm) for cm in c]) [] YAMLize a curve argument. >>> from .curve import Curve >>> c.append(CommandMessage('curve info', {'curve': Curve(path=None)})) - >>> print yaml.dump(c) # doctest: +REPORT_UDIFF + >>> print(yaml.dump(c)) # doctest: +REPORT_UDIFF !!python/object/new:hooke.command_stack.CommandStack listitems: - !!python/object:hooke.engine.CommandMessage @@ -306,7 +306,7 @@ class FileCommandStack (CommandStack): >>> c.append(CommandMessage('CommandB', {'param':'B'})) >>> c.append(CommandMessage('CommandA', {'param':'C'})) >>> c.append(CommandMessage('CommandB', {'param':'D'})) - >>> print c.flatten() + >>> print(c.flatten()) - arguments: {param: A} command: CommandA - arguments: {param: B} @@ -339,7 +339,7 @@ class FileCommandStack (CommandStack): ... ''' >>> c = FileCommandStack() >>> c.from_string(string) - >>> print [repr(cm) for cm in c] # doctest: +NORMALIZE_WHITESPACE + >>> print([repr(cm) for cm in c]) # doctest: +NORMALIZE_WHITESPACE ['', '', '', diff --git a/hooke/curve.py b/hooke/curve.py index d312be3..5367015 100644 --- a/hooke/curve.py +++ b/hooke/curve.py @@ -92,7 +92,7 @@ class Data (numpy.ndarray): >>> import yaml >>> s = yaml.dump(d) - >>> print s + >>> print(s) !hooke.curve.DataInfo columns: [distance (m), force (N)] @@ -188,7 +188,7 @@ class Curve (object): [}>] >>> z.command_stack[-1].arguments['curve'] == z True - >>> print yaml.dump(c) # doctest: +REPORT_UDIFF + >>> print(yaml.dump(c)) # doctest: +REPORT_UDIFF &id001 !!python/object:hooke.curve.Curve command_stack: !!python/object/new:hooke.command_stack.CommandStack listitems: @@ -214,7 +214,7 @@ class Curve (object): YAML still works, though. - >>> print yaml.dump(c.command_stack) # doctest: +REPORT_UDIFF + >>> print(yaml.dump(c.command_stack)) # doctest: +REPORT_UDIFF &id001 !!python/object/new:hooke.command_stack.CommandStack listitems: - !!python/object:hooke.engine.CommandMessage diff --git a/hooke/driver/jpk.py b/hooke/driver/jpk.py index 69f307e..368e5e0 100644 --- a/hooke/driver/jpk.py +++ b/hooke/driver/jpk.py @@ -55,10 +55,10 @@ def slash_join(*args): >>> sep = os.path.sep >>> os.path.sep = '/' - >>> print slash_join('abc', 'def/ghi', 'jkl\\mno') + >>> print(slash_join('abc', 'def/ghi', 'jkl\\mno')) abc/def/ghi/jkl\mno >>> os.path.sep = '\\' - >>> print slash_join('abc', 'def/ghi', 'jkl\\mno') + >>> print(slash_join('abc', 'def/ghi', 'jkl\\mno')) abc/def/ghi/jkl\mno >>> os.path.sep = sep diff --git a/hooke/driver/mcs.py b/hooke/driver/mcs.py index d96e2f6..4daa9d0 100644 --- a/hooke/driver/mcs.py +++ b/hooke/driver/mcs.py @@ -42,7 +42,7 @@ class mcsDriver(lib.driver.Driver): self.filename=filename self.othername=othername - #print self.filename, self.othername + #print('{} {}'.format(self.filename, self.othername)) self.filedata=open(filename,'rb') self.reddata=self.filedata.read() diff --git a/hooke/driver/wtk.py b/hooke/driver/wtk.py index 2f24e25..f6355c7 100644 --- a/hooke/driver/wtk.py +++ b/hooke/driver/wtk.py @@ -270,7 +270,7 @@ class WTKDriver (Driver): def _time_from_localtime_string(self, timestring, format="%Y%m%d%H%M%S"): """ - >>> print time.tzname + >>> print(time.tzname) ('EST', 'EDT') >>> d = WTKDriver() >>> d._time_from_localtime_string("19700101", format="%Y%m%d")/3600.0 diff --git a/hooke/engine.py b/hooke/engine.py index 0d02f1a..f2ab92c 100644 --- a/hooke/engine.py +++ b/hooke/engine.py @@ -62,17 +62,17 @@ class CommandMessage (QueueMessage): -------- >>> from .compat.odict import odict >>> cm = CommandMessage('command A') - >>> print unicode(cm) + >>> print(unicode(cm)) >>> cm.arguments = odict([('param a','value a'), ('param b', 'value b')]) - >>> print unicode(cm) + >>> print(unicode(cm)) The parameters are sorted by name, so you won't be surprised in any doctests, etc. >>> cm.arguments = odict([('param b','value b'), ('param a', 'value a')]) - >>> print unicode(cm) + >>> print(unicode(cm)) """ if len(self.arguments) > 0: diff --git a/hooke/hooke.py b/hooke/hooke.py index af7ec81..e056433 100644 --- a/hooke/hooke.py +++ b/hooke/hooke.py @@ -34,10 +34,10 @@ if False: # Queue pickle error debugging code feed = multiprocessing.queues.Queue._feed def new_feed (buffer, notempty, send, writelock, close): def s(obj): - print 'SEND:', obj, dir(obj) + print('SEND: {} {}'.format(obj, dir(obj))) for a in dir(obj): attr = getattr(obj, a) - #print ' ', a, attr, type(attr) + #print(' {} {} {}'.format(a, attr, type(attr))) if obj.__class__.__name__ == 'Hooke': # Set suspect attributes to None until you resolve the # PicklingError. Then fix whatever is breaking the @@ -242,8 +242,8 @@ def main(): help="Enable debug logging.") options,arguments = p.parse_args() if len(arguments) > 0: - print >> sys.stderr, 'More than 0 arguments to %s: %s' \ - % (sys.argv[0], arguments) + sys.stderr.write('More than 0 arguments to {}: {}\n'.format( + sys.argv[0], arguments)) p.print_help(sys.stderr) sys.exit(1) if options.config != None: @@ -254,7 +254,7 @@ def main(): runner = HookeRunner() if options.version == True: - print version() + print(version()) sys.exit(0) if options.debug == True: hooke.config.set( diff --git a/hooke/playlist.py b/hooke/playlist.py index 41779a5..a25e9d6 100644 --- a/hooke/playlist.py +++ b/hooke/playlist.py @@ -73,7 +73,7 @@ class NoteIndexList (list): try: self.__dict__.update(state) except TypeError, e: - print state, type(state), e + print(' '.join(str(x) for x in [state, type(state), e])) if self.info in [None, {}]: self.info = {} @@ -219,11 +219,11 @@ def playlist_path(path, expand=False): Examples -------- - >>> print playlist_path('playlist') + >>> print(playlist_path('playlist')) playlist.hkp - >>> print playlist_path('playlist.hkp') + >>> print(playlist_path('playlist.hkp')) playlist.hkp - >>> print playlist_path(None) + >>> print(playlist_path(None)) None """ if path == None: @@ -252,10 +252,10 @@ class FilePlaylist (Playlist): >>> s = pickle.dumps(p) >>> z = pickle.loads(s) >>> for curve in z: - ... print curve + ... print(curve) - >>> print z.drivers + >>> print(z.drivers) ['Driver A', 'Driver B'] The data-type is also YAMLable (see :mod:`hooke.util.yaml`). @@ -263,10 +263,10 @@ class FilePlaylist (Playlist): >>> s = yaml.dump(p) >>> z = yaml.load(s) >>> for curve in z: - ... print curve + ... print(curve) - >>> print z.drivers + >>> print(z.drivers) ['Driver A', 'Driver B'] """ version = '0.2' @@ -395,7 +395,7 @@ class FilePlaylist (Playlist): ... CommandMessage('command B', {'arg 0':1, 'curve':c}), ... ]) >>> p.append_curve(c) - >>> print p.flatten() # doctest: +REPORT_UDIFF + >>> print(p.flatten()) # doctest: +REPORT_UDIFF # Hooke playlist version 0.2 !!python/object/new:hooke.playlist.FilePlaylist listitems: @@ -429,7 +429,7 @@ class FilePlaylist (Playlist): version: '0.2' >>> p.relative_curve_paths = False - >>> print p.flatten() # doctest: +REPORT_UDIFF + >>> print(p.flatten()) # doctest: +REPORT_UDIFF # Hooke playlist version 0.2 !!python/object/new:hooke.playlist.FilePlaylist listitems: @@ -508,7 +508,7 @@ def from_string(string): >>> p = from_string(string) >>> p.set_path('/path/to/playlist') >>> for curve in p: - ... print curve.name, curve.path + ... print('{} {}'.format(curve.name, curve.path)) one /path/to/curve/one two /path/to/curve/two @@ -552,7 +552,7 @@ def from_string(string): >>> p.info {'note': 'An example playlist'} >>> for curve in p: - ... print curve.name, curve.path + ... print('{} {}'.format(curve.name, curve.path)) one /path/to/curve/one two /path/to/curve/two >>> p[-1].info['attr with spaces'] diff --git a/hooke/plugin/curve.py b/hooke/plugin/curve.py index d9cda88..6c13c6c 100644 --- a/hooke/plugin/curve.py +++ b/hooke/plugin/curve.py @@ -813,21 +813,22 @@ class OldCruft (object): maxpoint=True if rebase: - print 'Select baseline' + print('Select baseline') self.basepoints=self._measure_N_points(N=2, whatset=whatset) self.basecurrent=self.current.path if maxpoint: - print 'Select two points' + print('Select two points') points=self._measure_N_points(N=2, whatset=whatset) boundpoints=[points[0].index, points[1].index] boundpoints.sort() try: y=min(plot.vectors[whatset][1][boundpoints[0]:boundpoints[1]]) except ValueError: - print 'Chosen interval not valid. Try picking it again. Did you pick the same point as begin and end of interval?' + print('Chosen interval not valid. Try picking it again. Did ' + 'you pick the same point as begin and end of interval?') else: - print 'Select point to measure' + print('Select point to measure') points=self._measure_N_points(N=1, whatset=whatset) #whatplot=points[0].dest y=points[0].graph_coords[1] @@ -839,7 +840,7 @@ class OldCruft (object): avg=np.mean(to_average) forcebase=abs(y-avg) - print str(forcebase*(10**12))+' pN' + print('{} pN'.format(forcebase * 10**12)) to_dump='forcebase '+self.current.path+' '+str(forcebase*(10**12))+' pN' self.outlet.push(to_dump) @@ -868,17 +869,17 @@ class OldCruft (object): # Decides between the two forms of user input, as per (args) if fitspan == 0: # Gets the Xs of two clicked points as indexes on the current curve vector - print 'Click twice to delimit chunk' + print('Click twice to delimit chunk') points=self._measure_N_points(N=2,whatset=1) else: - print 'Click once on the leftmost point of the chunk (i.e.usually the peak)' + print('Click once on the leftmost point of the chunk (i.e.usually the peak)') points=self._measure_N_points(N=1,whatset=1) slope=self._slope(points,fitspan) # Outputs the relevant slope parameter - print 'Slope:' - print str(slope) + print('Slope:') + print(str(slope)) to_dump='slope '+self.current.path+' '+str(slope) self.outlet.push(to_dump) @@ -894,12 +895,12 @@ class OldCruft (object): try: parameters=self.linefit_between(clickedpoints[0],clickedpoints[1]) except: - print 'Cannot fit. Did you click twice the same point?' + print('Cannot fit. Did you click twice the same point?') return # Outputs the relevant slope parameter - print 'Slope:' - print str(parameters[0]) + print('Slope:') + print(str(parameters[0])) to_dump='slope '+self.curve.path+' '+str(parameters[0]) self.outlet.push(to_dump) diff --git a/hooke/plugin/polymer_fit.py b/hooke/plugin/polymer_fit.py index 33e0c75..31036cd 100644 --- a/hooke/plugin/polymer_fit.py +++ b/hooke/plugin/polymer_fit.py @@ -232,9 +232,9 @@ class FJC (ModelFitter): >>> outqueue = Queue() >>> L,a = model.fit(outqueue=outqueue) >>> fit_info = outqueue.get(block=False) - >>> print L + >>> print(L) 3.5e-08 - >>> print a + >>> print(a) 2.5e-10 Fit the example data with a one-parameter fit (`L`). We introduce @@ -244,7 +244,7 @@ class FJC (ModelFitter): >>> model = FJC(d_data, info=info, rescale=True) >>> L, = model.fit(outqueue=outqueue) >>> fit_info = outqueue.get(block=False) - >>> print L # doctest: +ELLIPSIS + >>> print(L) # doctest: +ELLIPSIS 3.199...e-08 """ def Lp(self, L): @@ -493,9 +493,9 @@ class FJC_PEG (ModelFitter): >>> outqueue = Queue() >>> N,a = model.fit(outqueue=outqueue) >>> fit_info = outqueue.get(block=False) - >>> print N + >>> print(N) 123.0 - >>> print a + >>> print(a) 7e-10 Fit the example data with a one-parameter fit (`N`). We introduce @@ -505,7 +505,7 @@ class FJC_PEG (ModelFitter): >>> model = FJC_PEG(d_data, info=info, rescale=True) >>> N, = model.fit(outqueue=outqueue) >>> fit_info = outqueue.get(block=False) - >>> print N # doctest: +ELLIPSIS + >>> print(N) # doctest: +ELLIPSIS 96.931... """ def Lr(self, L): @@ -710,9 +710,9 @@ class WLC (ModelFitter): >>> outqueue = Queue() >>> L,p = model.fit(outqueue=outqueue) >>> fit_info = outqueue.get(block=False) - >>> print L + >>> print(L) 3.5e-08 - >>> print p + >>> print(p) 2.5e-10 Fit the example data with a one-parameter fit (`L`). We introduce @@ -722,7 +722,7 @@ class WLC (ModelFitter): >>> model = WLC(d_data, info=info, rescale=True) >>> L, = model.fit(outqueue=outqueue) >>> fit_info = outqueue.get(block=False) - >>> print L # doctest: +ELLIPSIS + >>> print(L) # doctest: +ELLIPSIS 3.318...e-08 """ def Lp(self, L): diff --git a/hooke/ui/gui/panel/plot.py b/hooke/ui/gui/panel/plot.py index 4191495..54ca57a 100644 --- a/hooke/ui/gui/panel/plot.py +++ b/hooke/ui/gui/panel/plot.py @@ -261,7 +261,7 @@ class PlotPanel (Panel, wx.Panel): self.Refresh() def OnPaint(self, event): - print 'painting' + print('painting') super(PlotPanel, self).OnPaint(event) self._c['canvas'].draw() diff --git a/hooke/ui/gui/panel/propertyeditor-propgrid.py b/hooke/ui/gui/panel/propertyeditor-propgrid.py index 93bb092..27a1532 100644 --- a/hooke/ui/gui/panel/propertyeditor-propgrid.py +++ b/hooke/ui/gui/panel/propertyeditor-propgrid.py @@ -255,7 +255,7 @@ class LargeImageEditor(wxpg.PyEditor): return (lipc, btn) except: import traceback - print traceback.print_exc() + print(traceback.print_exc()) def UpdateControl(self, property, ctrl): ctrl.SetValue(property.GetDisplayedString()) diff --git a/hooke/util/callback.py b/hooke/util/callback.py index 53b6e29..d4c870c 100644 --- a/hooke/util/callback.py +++ b/hooke/util/callback.py @@ -64,11 +64,11 @@ def callback(method): returned arguments of the method they're attached to. >>> def c(self, method, *args): - ... print '\\n '.join([ + ... print('\\n '.join([ ... 'callback:', ... 'class: %s' % self, ... 'method: %s' % method, - ... 'returned: %s' % args]) + ... 'returned: %s' % args])) For some class, decorate any functions you're interested in attaching callbacks too. Also, add a `_callbacks` attribute @@ -81,13 +81,13 @@ def callback(method): ... @callback ... def xyz(self): ... "xyz's docstring" - ... print 'usual xyz business' + ... print('usual xyz business') ... return (0, 1, 1, 2, 3, 5) ... ... @callback ... def abc(self): ... "abc's docstring" - ... print 'usual abc business' + ... print('usual abc business') ... >>> x = X() @@ -104,7 +104,7 @@ def callback(method): The decorated method preserves the original docstring. - >>> print x.xyz.__doc__ + >>> print(x.xyz.__doc__) xyz's docstring So far, we haven't attached a callback to `abc`. @@ -126,7 +126,7 @@ def callback(method): array of callbacks in series. >>> def d(self, method, *args): - ... print 'callback d' + ... print('callback d') >>> x._callbacks['abc'] = [d, c, d] >>> r = x.abc() # doctest: +ELLIPSIS usual abc business @@ -169,12 +169,12 @@ def in_callback(self, *args, **kwargs): returned arguments of the method they're attached to. >>> def c(self, method, *args, **kwargs): - ... print '\\n '.join([ + ... print('\\n '.join([ ... 'callback:', ... 'class: %s' % self, ... 'method: %s' % method, ... 'args: %s' % (args,), - ... 'kwargs: %s' % kwargs]) + ... 'kwargs: %s' % kwargs])) Now place `in_callback` calls inside any interesting methods. @@ -184,14 +184,14 @@ def in_callback(self, *args, **kwargs): ... ... def xyz(self): ... "xyz's docstring" - ... print 'usual xyz business' + ... print('usual xyz business') ... in_callback(self, 5, my_kw=17) ... return (0, 1, 1, 2, 3, 5) ... ... def abc(self): ... "abc's docstring" ... in_callback(self, p1=3.14, p2=159) - ... print 'usual abc business' + ... print('usual abc business') ... >>> x = X() @@ -227,7 +227,7 @@ def in_callback(self, *args, **kwargs): array of callbacks in series. >>> def d(self, method, *args, **kwargs): - ... print 'callback d' + ... print('callback d') >>> x._callbacks['abc'] = [d, c, d] >>> r = x.abc() # doctest: +ELLIPSIS callback d diff --git a/hooke/util/caller.py b/hooke/util/caller.py index 2384439..dee741d 100644 --- a/hooke/util/caller.py +++ b/hooke/util/caller.py @@ -57,7 +57,7 @@ def caller_name(depth=1): >>> def x(depth): ... y(depth) >>> def y(depth): - ... print caller_name(depth) + ... print(caller_name(depth)) >>> x(1) y >>> x(2) @@ -89,7 +89,7 @@ def caller_names(depth=1): >>> def y(): ... z() >>> def z(): - ... print list(caller_names()) + ... print(list(caller_names())) >>> x() # doctest: +ELLIPSIS ['z', 'y', 'x', ...] >>> y() # doctest: +ELLIPSIS diff --git a/hooke/util/fit.py b/hooke/util/fit.py index 785355e..f0bf32c 100644 --- a/hooke/util/fit.py +++ b/hooke/util/fit.py @@ -115,9 +115,9 @@ class ModelFitter (object): machine rounding during computation. We expect the values to be close to the input settings (slope 7, offset -33). - >>> print '%.3f' % slope + >>> print('{:.3f}'.format(slope)) 7.000 - >>> print '%.3f' % offset + >>> print('{:.3f}'.format(offset)) -32.890 The offset is a bit off because, the range is not a multiple of @@ -128,9 +128,9 @@ class ModelFitter (object): >>> m = LinearModel(data, rescale=True) >>> outqueue = Queue() >>> slope,offset = m.fit(outqueue=outqueue) - >>> print '%.3f' % slope + >>> print('{:.3f}'.format(slope)) 7.000 - >>> print '%.3f' % offset + >>> print('{:.3f}'.format(offset)) -32.890 Test single-parameter models: @@ -149,7 +149,7 @@ class ModelFitter (object): >>> data = 20*numpy.sin(arange(1000)) + 7.*arange(1000) >>> m = SingleParameterModel(data) >>> slope, = m.fit(outqueue=outqueue) - >>> print '%.3f' % slope + >>> print('{:.3f}'.format(slope)) 7.000 """ def __init__(self, *args, **kwargs): @@ -285,7 +285,7 @@ class ModelFitter (object): # def dist(px,py,linex,liney): # distancesx=scipy.array([(px-x)**2 for x in linex]) # minindex=numpy.argmin(distancesx) -# print px, linex[0], linex[-1] +# print(px, linex[0], linex[-1]) # return (py-liney[minindex])**2 # # diff --git a/hooke/util/graph.py b/hooke/util/graph.py index 69f392b..cecb045 100644 --- a/hooke/util/graph.py +++ b/hooke/util/graph.py @@ -43,20 +43,20 @@ class Node (list): We can list all of a node's ancestors. - >>> print [node for node in d.ancestors()] + >>> print([node for node in d.ancestors()]) [b, c, a] - >>> print [node for node in d.ancestors(depth_first=True)] + >>> print([node for node in d.ancestors(depth_first=True)]) [b, a, c] Ancestors works with cycles. >>> a.append(d) - >>> print [node for node in d.ancestors()] + >>> print([node for node in d.ancestors()]) [b, c, a, d] We can find the cycle path. - >>> print d.parent_path(d) + >>> print(d.parent_path(d)) [b, a, d] After a run through :meth:`Graph.set_children`, we can also @@ -64,12 +64,12 @@ class Node (list): >>> g = Graph([a, b, c, d]) >>> g.set_children() - >>> print a.children + >>> print(a.children) [b, c] And descendents. - >>> print [node for node in a.descendents(depth_first=True)] + >>> print([node for node in a.descendents(depth_first=True)]) [b, d, a, c] """ def __init__(self, parents=[], data=None): @@ -327,7 +327,7 @@ class GraphRowGenerator (list): p = GraphRowPrinter(tip_to_root=tip_to_root) for node in nodes: g.insert(node) - print p(g[-1]) + print(p(g[-1])) For the split/join branch columns, "born" and "dead" are defined from the point of view of `GraphRow`. For root-to-tip ordering @@ -403,9 +403,9 @@ class Graph (list): >>> n.i.extend([n.f, n.g, n.h]) >>> g = Graph([n.a,n.b,n.c,n.d,n.e,n.f,n.g,n.h,n.i]) >>> g.topological_sort(tip_to_root=True) - >>> print [node for node in g] + >>> print([node for node in g]) [i, h, g, f, e, d, c, b, a] - >>> print g.ascii_graph() + >>> print(g.ascii_graph()) r-\-\ a | | * b | * | c @@ -415,7 +415,7 @@ class Graph (list): | * | g * | | h t-/-/ i - >>> print g.ascii_graph(tip_to_root=True) + >>> print(g.ascii_graph(tip_to_root=True)) t-\-\ i | | * h | * | g @@ -436,7 +436,7 @@ class Graph (list): >>> n.g.extend([n.e, n.f]) >>> n.h.extend([n.c, n.g]) >>> g = Graph([n.a,n.b,n.c,n.d,n.e,n.f,n.g,n.h]) - >>> print g.ascii_graph(tip_to_root=True) + >>> print(g.ascii_graph(tip_to_root=True)) t-\ h | *-\ g | | *-\ f @@ -452,7 +452,7 @@ class Graph (list): ... nx = getattr(n, char) ... n.i.append(nx) >>> g = Graph([n.a,n.b,n.c,n.d,n.e,n.f,n.g,n.h,n.i]) - >>> print g.ascii_graph(tip_to_root=True) + >>> print(g.ascii_graph(tip_to_root=True)) t-\-\-\-\-\-\-\ i | | | | | | | r h | | | | | | r g @@ -469,7 +469,7 @@ class Graph (list): ... nx = getattr(n, char) ... nx.append(n.a) >>> g = Graph([n.a,n.b,n.c,n.d,n.e,n.f,n.g,n.h,n.i]) - >>> print g.ascii_graph(tip_to_root=True) + >>> print(g.ascii_graph(tip_to_root=True)) t i | t h | | t g @@ -489,7 +489,7 @@ class Graph (list): >>> n.h.extend([n.a, n.c, n.d, n.g]) >>> n.i.extend([n.a, n.b, n.c, n.g]) >>> g = Graph([n.a,n.b,n.c,n.d,n.e,n.f,n.g,n.h,n.i]) - >>> print g.ascii_graph(tip_to_root=True) + >>> print(g.ascii_graph(tip_to_root=True)) t-\-\-\ i | | | | t-\-\-\ h | | | *-|-|-|-<-\ g diff --git a/hooke/util/peak.py b/hooke/util/peak.py index 3ca7572..e5adf39 100644 --- a/hooke/util/peak.py +++ b/hooke/util/peak.py @@ -382,7 +382,7 @@ def merge_double_peaks(data, peaks, see_double=10): ... Peak(name='c', index=23, values=data[23:27]), ... Peak(name='d', index=100, values=data[100:101])] >>> peaks = merge_double_peaks(data, peaks, see_double=10) - >>> print '\\n'.join([str(p) for p in peaks]) + >>> print('\\n'.join([str(p) for p in peaks])) >>> min(peaks[0].values == data[10:27]) @@ -434,7 +434,7 @@ def drop_narrow_peaks(peaks, min_points=1): ... Peak(name='c', index=23, values=data[23:27]), ... Peak(name='d', index=100, values=data[100:101])] >>> peaks = drop_narrow_peaks(peaks, min_points=3) - >>> print '\\n'.join([str(p) for p in peaks]) + >>> print('\\n'.join([str(p) for p in peaks])) """ diff --git a/hooke/util/quickhull.py b/hooke/util/quickhull.py index 1b54165..39e4274 100644 --- a/hooke/util/quickhull.py +++ b/hooke/util/quickhull.py @@ -98,17 +98,17 @@ def points_inside_hull(hull, points): return inside def print_postscript(sample, hull): - print "%!" - print "100 500 translate 2 2 scale 0 0 moveto" - print "/tick {moveto 0 2 rlineto 0 -4 rlineto 0 2 rlineto" - print " 2 0 rlineto -4 0 rlineto 2 0 rlineto} def" + print('%!') + print('100 500 translate 2 2 scale 0 0 moveto') + print('/tick {moveto 0 2 rlineto 0 -4 rlineto 0 2 rlineto') + print(' 2 0 rlineto -4 0 rlineto 2 0 rlineto} def') for (x,y) in sample: - print x, y, "tick" - print "stroke" - print hull[0,0], hull[0,1], "moveto" + print('{} {} tick'.format(x, y)) + print('stroke') + print(hull[0,0], hull[0,1], 'moveto') for (x,y) in hull[1:]: - print x, y, "lineto" - print "closepath stroke showpage" + print('{} {} lineto'.format(x, y)) + print('closepath stroke showpage') if __name__ == "__main__": #sample = 10*array([(x,y) for x in arange(10) for y in arange(10)]) diff --git a/hooke/util/si.py b/hooke/util/si.py index 2a36bb3..9d6e910 100644 --- a/hooke/util/si.py +++ b/hooke/util/si.py @@ -30,11 +30,11 @@ Get the power from the first (or last, or middle, ...) value >>> p = get_power(xs[0]) >>> for x in xs: -... print ppSI(x, decimals=2, power=p) +... print(ppSI(x, decimals=2, power=p)) 985.00 p 1000.00 p 112358.00 p ->>> print prefix_from_value(xs[0]) + 'N' +>>> print(prefix_from_value(xs[0]) + 'N') pN """ @@ -87,13 +87,13 @@ def ppSI(value, unit='', decimals=None, power=None, pad=False): Examples -------- >>> x = math.pi * 1e-8 - >>> print ppSI(x, 'N') + >>> print(ppSI(x, 'N')) 31.415927 nN - >>> print ppSI(x, 'N', 3) + >>> print(ppSI(x, 'N', 3)) 31.416 nN - >>> print ppSI(x, 'N', 4, power=-12) + >>> print(ppSI(x, 'N', 4, power=-12)) 31415.9265 pN - >>> print ppSI(x, 'N', 5, pad=True) + >>> print(ppSI(x, 'N', 5, pad=True)) 31.41593 nN If you want the decimal indented by six spaces with `decimal=2`, @@ -103,7 +103,7 @@ def ppSI(value, unit='', decimals=None, power=None, pad=False): * 1 (length of the decimal point) * 2 (places after the decimal point) - >>> print ppSI(-x, 'N', 2, pad=(6+1+2)) + >>> print(ppSI(-x, 'N', 2, pad=(6+1+2))) -31.42 nN """ if value == 0: diff --git a/hooke/util/singleton.py b/hooke/util/singleton.py index d0bc4ce..0b974fd 100644 --- a/hooke/util/singleton.py +++ b/hooke/util/singleton.py @@ -19,13 +19,13 @@ >>> class A (Singleton): ... def init(self): -... print 'initializing instance of %s at (%s)' % ( -... self.__class__.__name__, id(self)) +... print('initializing instance of {} at ({})'.format( +... self.__class__.__name__, id(self))) >>> A_instances = [A() for i in range(3)] # doctest: +ELLIPSIS initializing instance of A at (...) >>> for i in A_instances[1:]: -... print id(i) == id(A_instances[0]) +... print(id(i) == id(A_instances[0])) True True @@ -36,7 +36,7 @@ Singletons can also be subclassed. >>> B_instances = [B() for i in range(3)] # doctest: +ELLIPSIS initializing instance of B at (...) >>> for i in B_instances[1:]: -... print id(i) == id(B_instances[0]) +... print(id(i) == id(B_instances[0])) True True >>> id(A_instances[0]) == id(B_instances[0]) diff --git a/hooke/util/yaml.py b/hooke/util/yaml.py index e66a686..956db41 100644 --- a/hooke/util/yaml.py +++ b/hooke/util/yaml.py @@ -24,7 +24,7 @@ stored somewhere else or not important. >>> import yaml >>> a = numpy.array([1,2,3]) ->>> print yaml.dump(a) +>>> print(yaml.dump(a)) null ... @@ -33,7 +33,7 @@ The default behavior is to crash. >>> yaml.Dumper.yaml_representers.pop(numpy.ndarray) # doctest: +ELLIPSIS ->>> print yaml.dump(a) # doctest: +REPORT_UDIFF +>>> print(yaml.dump(a)) # doctest: +REPORT_UDIFF !!python/object/apply:numpy.core.multiarray._reconstruct args: - !!python/name:numpy.ndarray '' @@ -101,7 +101,8 @@ if False: # YAML dump debugging code define new types (e.g. numpy.ndarray) which YAML cannot inspect. """ def ignore_aliases(data): - print data, repr(data), type(data), repr(type(data)) + print(' '.join(str(x) for x in [ + data, repr(data), type(data), repr(type(data))])) sys.stdout.flush() if data in [None, ()]: return True diff --git a/test/apply_command_stack_to_playlist.py b/test/apply_command_stack_to_playlist.py index 5657727..2a5bdd1 100644 --- a/test/apply_command_stack_to_playlist.py +++ b/test/apply_command_stack_to_playlist.py @@ -123,7 +123,7 @@ unloading curve 0x07200000 engine message from apply command stack to playlist (): >>> for c in curve.command_stack: -... print c # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE, +REPORT_UDIFF +... print(c) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE, +REPORT_UDIFF ...}> diff --git a/test/block_info.py b/test/block_info.py index 4d37b7a..e92fa14 100644 --- a/test/block_info.py +++ b/test/block_info.py @@ -42,7 +42,7 @@ Success ... text = f.read() >>> if block_info_already_exists == False: ... os.remove(file_name) ->>> print text # doctest: +ELLIPSIS, +REPORT_UDIFF +>>> print(text) # doctest: +ELLIPSIS, +REPORT_UDIFF picoforce.000: approach: columns: [z piezo (m), deflection (m)] diff --git a/test/command_stack_save_load.py b/test/command_stack_save_load.py index c06b91a..591d00f 100644 --- a/test/command_stack_save_load.py +++ b/test/command_stack_save_load.py @@ -75,7 +75,7 @@ Success >>> os.listdir(target_dir) ['default'] >>> with open(os.path.join(target_dir, 'default'), 'r') as f: -... print f.read() +... print(f.read()) - arguments: {input: test/data/test} command: load playlist - arguments: {} @@ -90,7 +90,7 @@ Success >>> sorted(os.listdir(target_dir)) ['default', 'my_stack'] >>> with open(os.path.join(target_dir, 'my_stack'), 'r') as f: -... print f.read() +... print(f.read()) - arguments: {input: test/data/test} command: load playlist - arguments: {} @@ -112,14 +112,14 @@ Success Success >>> with open(os.path.join(target_dir, 'default'), 'r') as f: -... print f.read() +... print(f.read()) - arguments: {input: test/data/test} command: load playlist - arguments: {} command: get curve >>> with open(os.path.join(target_dir, 'my_stack'), 'r') as f: -... print f.read() +... print(f.read()) - arguments: {input: test/data/test} command: load playlist - arguments: {} @@ -144,7 +144,7 @@ Success Success >>> with open(os.path.join(target_dir, 'default'), 'r') as f: -... print f.read() +... print(f.read()) - arguments: {} command: version diff --git a/test/export_block.py b/test/export_block.py index 6dedb12..410c9cf 100644 --- a/test/export_block.py +++ b/test/export_block.py @@ -38,9 +38,10 @@ Success ... lines = f.readlines() >>> if export_already_exists == False: ... os.remove(file_name) ->>> print len(lines) +>>> len(lines) 2049 ->>> print ''.join(lines[:5]), # doctest: +ELLIPSIS, +REPORT_UDIFF +NORMALIZE_WHITESPACE +>>> print(''.join(lines[:5]).rstrip()) +... # doctest: +ELLIPSIS, +REPORT_UDIFF +NORMALIZE_WHITESPACE # z piezo (m) deflection (m) -1.519...e-07 9.094...e-08 -1.513...e-07 9.130...e-08 diff --git a/test/jpk_driver.py b/test/jpk_driver.py index 022b256..63521a6 100644 --- a/test/jpk_driver.py +++ b/test/jpk_driver.py @@ -42,9 +42,9 @@ Ensure that we can at least load each of the example curves. >>> p = h.playlists.current() >>> for i,curve in enumerate(p.items()): -... print (i, +... print((i, ... curve.info['raw info']['file-format-version'], -... [d.info['name'] for d in curve.data]) # doctest: +REPORT_UDIFF +... [d.info['name'] for d in curve.data])) # doctest: +REPORT_UDIFF (0, '0.5', ['approach', 'retract']) (1, '0.5', ['approach', 'pause', 'retract']) (2, '0.2', ['pause-0', 'approach', 'pause-1', 'retract']) @@ -58,10 +58,10 @@ Load each of the example segments in the :file:`Data1D` directory. >>> base_dir = os.path.join('test', 'data', 'vclamp_jpk', 'Data1D') >>> for file_name in sorted(os.listdir(base_dir)): ... path = os.path.join(base_dir, file_name) -... print path -... print driver.is_me(path) +... print(path) +... print(driver.is_me(path)) ... data = driver.read(path) -... print data.shape, data[:5], data[-5:] +... print(' '.join(str(x) for x in [data.shape, data[:5], data[-5:]])) ... # doctest: +ELLIPSIS, +REPORT_UDIFF test/data/vclamp_jpk/Data1D/data1D-ConstantData1D-1282315524304.jpk-data1D True diff --git a/test/multiple_curve_analysis.py b/test/multiple_curve_analysis.py index 4bc5726..9463433 100644 --- a/test/multiple_curve_analysis.py +++ b/test/multiple_curve_analysis.py @@ -71,7 +71,7 @@ Verify successful application. >>> curve >>> for c in curve.command_stack: -... print c # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE, +REPORT_UDIFF +... print(c) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE, +REPORT_UDIFF @@ -80,7 +80,7 @@ Verify successful application. >>> for c in curve.data[-1].info['columns']: -... print c # doctest: +REPORT_UDIFF +... print(c) # doctest: +REPORT_UDIFF z piezo (m) deflection (m) surface distance (m) @@ -94,7 +94,7 @@ polymer peak 0 (N) >>> curve >>> for c in curve.command_stack: -... print c # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE, +REPORT_UDIFF +... print(c) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE, +REPORT_UDIFF @@ -103,7 +103,7 @@ polymer peak 0 (N) >>> for c in curve.data[-1].info['columns']: -... print c # doctest: +REPORT_UDIFF +... print(c) # doctest: +REPORT_UDIFF z piezo (m) deflection (m) surface distance (m)