Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Refactor raw print statements in accordance with 2to3

Removed prints in a couple places entirely, some of this
code should likely use the `logging` module instead
  • Loading branch information...
commit 0b8c21f8f3cc5f95f2184bf717b62f2888ed4935 1 parent a23cfe7
R. Tyler Croy rtyler authored
2  SetupConfig.py
@@ -71,7 +71,7 @@
71 71 ]
72 72 }
73 73 except ImportError:
74   - print 'Not using setuptools, so we cannot install the Markdown dependency'
  74 + print('Not using setuptools, so we cannot install the Markdown dependency')
75 75
76 76
77 77 description = "Cheetah is a template engine and code generation tool."
12 SetupTools.py
@@ -158,14 +158,14 @@ def run_setup(configurations):
158 158 try:
159 159 apply(setup, (), kws)
160 160 except BuildFailed, x:
161   - print "One or more C extensions failed to build."
162   - print "Details: %s" % x
163   - print "Retrying without C extensions enabled."
  161 + print("One or more C extensions failed to build.")
  162 + print("Details: %s" % x)
  163 + print("Retrying without C extensions enabled.")
164 164
165 165 del kws['ext_modules']
166 166 apply(setup, (), kws)
167 167
168   - print "One or more C extensions failed to build."
169   - print "Performance enhancements will not be available."
170   - print "Pure Python installation succeeded."
  168 + print("One or more C extensions failed to build.")
  169 + print("Performance enhancements will not be available.")
  170 + print("Pure Python installation succeeded.")
171 171
8 cheetah/CheetahWrapper.py
@@ -195,14 +195,14 @@ def parseOpts(self, args):
195 195
196 196
197 197 if opts.print_settings:
198   - print
199   - print '>> Available Cheetah compiler settings:'
  198 + print()
  199 + print('>> Available Cheetah compiler settings:')
200 200 from Cheetah.Compiler import _DEFAULT_COMPILER_SETTINGS
201 201 listing = _DEFAULT_COMPILER_SETTINGS
202 202 listing.sort(key=lambda l: l[0][0].lower())
203 203
204 204 for l in listing:
205   - print '\t%s (default: "%s")\t%s' % l
  205 + print('\t%s (default: "%s")\t%s' % l)
206 206 sys.exit(0)
207 207
208 208 #cleanup trailing path separators
@@ -266,7 +266,7 @@ def test(self):
266 266 runner.run(unittest.TestSuite(Test.suites))
267 267
268 268 def version(self):
269   - print Version
  269 + print(Version)
270 270
271 271 # If you add a command, also add it to the 'meths' variable in main().
272 272
24 cheetah/Filters.py
@@ -65,9 +65,9 @@ def filter(self, value, **kwargs):
65 65 try:
66 66 import markdown
67 67 except ImportError:
68   - print '>>> Exception raised importing the "markdown" module'
69   - print '>>> Are you sure you have the ElementTree module installed?'
70   - print ' http://effbot.org/downloads/#elementtree'
  68 + print('>>> Exception raised importing the "markdown" module')
  69 + print('>>> Are you sure you have the ElementTree module installed?')
  70 + print(' http://effbot.org/downloads/#elementtree')
71 71 raise
72 72
73 73 encoded = super(Markdown, self).filter(value, **kwargs)
@@ -97,8 +97,8 @@ def filter(self, source, **kwargs):
97 97 from pygments import lexers
98 98 from pygments import formatters
99 99 except ImportError, ex:
100   - print '<%s> - Failed to import pygments! (%s)' % (self.__class__.__name__, ex)
101   - print '-- You may need to install it from: http://pygments.org'
  100 + print('<%s> - Failed to import pygments! (%s)' % (self.__class__.__name__, ex))
  101 + print('-- You may need to install it from: http://pygments.org')
102 102 return encoded
103 103
104 104 lexer = None
@@ -196,15 +196,15 @@ def filter(self, val, **kw):
196 196 def test():
197 197 s1 = "abc <=> &"
198 198 s2 = " asdf \n\t 1 2 3\n"
199   - print "WebSafe INPUT:", `s1`
200   - print " WebSafe:", `WebSafe().filter(s1)`
  199 + print("WebSafe INPUT:", `s1`)
  200 + print(" WebSafe:", `WebSafe().filter(s1)`)
201 201
202   - print
203   - print " Strip INPUT:", `s2`
204   - print " Strip:", `Strip().filter(s2)`
205   - print "StripSqueeze:", `StripSqueeze().filter(s2)`
  202 + print()
  203 + print(" Strip INPUT:", `s2`)
  204 + print(" Strip:", `Strip().filter(s2)`)
  205 + print("StripSqueeze:", `StripSqueeze().filter(s2)`)
206 206
207   - print "Unicode:", `EncodeUnicode().filter(u'aoeu12345\u1234')`
  207 + print("Unicode:", `EncodeUnicode().filter(u'aoeu12345\u1234')`)
208 208
209 209 if __name__ == "__main__":
210 210 test()
4 cheetah/ImportManager.py
@@ -223,8 +223,8 @@ def getmod(self, nm,
223 223 co = compile(open(py[0], 'r').read()+'\n', py[0], 'exec')
224 224 break
225 225 except SyntaxError, e:
226   - print "Invalid syntax in %s" % py[0]
227   - print e.args
  226 + print("Invalid syntax in %s" % py[0])
  227 + print(e.args)
228 228 raise
229 229 elif pyc:
230 230 stuff = open(pyc[0], 'rb').read()
14 cheetah/NameMapper.py
@@ -364,13 +364,13 @@ def function(whichOne='default'):
364 364 }
365 365 b = 'this is local b'
366 366
367   - print valueForKey(a.dic,'subDict')
368   - print valueForName(a, 'dic.item')
369   - print valueForName(vars(), 'b')
370   - print valueForName(__builtins__, 'dir')()
371   - print valueForName(vars(), 'a.classVar')
372   - print valueForName(vars(), 'a.dic.func', executeCallables=True)
373   - print valueForName(vars(), 'a.method2.item1', executeCallables=True)
  367 + print(valueForKey(a.dic,'subDict'))
  368 + print(valueForName(a, 'dic.item'))
  369 + print(valueForName(vars(), 'b'))
  370 + print(valueForName(__builtins__, 'dir')())
  371 + print(valueForName(vars(), 'a.classVar'))
  372 + print(valueForName(vars(), 'a.dic.func', executeCallables=True))
  373 + print(valueForName(vars(), 'a.method2.item1', executeCallables=True))
374 374
375 375 if __name__ == '__main__':
376 376 example()
40 cheetah/Parser.py
... ... @@ -1,21 +1,12 @@
1   -# $Id: Parser.py,v 1.137 2008/03/10 05:25:13 tavis_rudd Exp $
2   -"""Parser classes for Cheetah's Compiler
  1 +"""
  2 +Parser classes for Cheetah's Compiler
3 3
4 4 Classes:
5 5 ParseError( Exception )
6 6 _LowLevelParser( Cheetah.SourceReader.SourceReader ), basically a lexer
7 7 _HighLevelParser( _LowLevelParser )
8 8 Parser === _HighLevelParser (an alias)
9   -
10   -Meta-Data
11   -================================================================================
12   -Author: Tavis Rudd <tavis@damnsimple.com>
13   -Version: $Revision: 1.137 $
14   -Start Date: 2001/08/01
15   -Last Revision Date: $Date: 2008/03/10 05:25:13 $
16 9 """
17   -__author__ = "Tavis Rudd <tavis@damnsimple.com>"
18   -__revision__ = "$Revision: 1.137 $"[11:-2]
19 10
20 11 import os
21 12 import sys
@@ -1224,7 +1215,6 @@ def transformToken(self, token, beforeTokenPos):
1224 1215 startPosIdx = 3
1225 1216 else:
1226 1217 startPosIdx = 1
1227   - #print 'CHEETAH STRING', nextToken, theStr, startPosIdx
1228 1218 self.setPos(beforeTokenPos+startPosIdx+1)
1229 1219 outputExprs = []
1230 1220 strConst = ''
@@ -1240,8 +1230,6 @@ def transformToken(self, token, beforeTokenPos):
1240 1230 self.setPos(endPos)
1241 1231 if strConst:
1242 1232 outputExprs.append(repr(strConst))
1243   - #if not self.atEnd() and self.matches('.join('):
1244   - # print 'DEBUG***'
1245 1233 token = "''.join(["+','.join(outputExprs)+"])"
1246 1234 return token
1247 1235
@@ -1854,13 +1842,11 @@ def eatCompiler(self):
1854 1842 try:
1855 1843 self._compiler.setCompilerSetting(settingName, valueExpr)
1856 1844 except:
1857   - out = sys.stderr
1858   - print >> out, 'An error occurred while processing the following #compiler directive.'
1859   - print >> out, '-'*80
1860   - print >> out, self[startPos:endPos]
1861   - print >> out, '-'*80
1862   - print >> out, 'Please check the syntax of these settings.'
1863   - print >> out, 'A full Python exception traceback follows.'
  1845 + sys.stderr.write('An error occurred while processing the following #compiler directive.\n')
  1846 + sys.stderr.write('----------------------------------------------------------------------\n')
  1847 + sys.stderr.write('%s\n' % self[startPos:endPos])
  1848 + sys.stderr.write('----------------------------------------------------------------------\n')
  1849 + sys.stderr.write('Please check the syntax of these settings.\n\n')
1864 1850 raise
1865 1851
1866 1852
@@ -1890,13 +1876,11 @@ def eatCompilerSettings(self):
1890 1876 try:
1891 1877 self._compiler.setCompilerSettings(keywords=keywords, settingsStr=settingsStr)
1892 1878 except:
1893   - out = sys.stderr
1894   - print >> out, 'An error occurred while processing the following compiler settings.'
1895   - print >> out, '-'*80
1896   - print >> out, settingsStr.strip()
1897   - print >> out, '-'*80
1898   - print >> out, 'Please check the syntax of these settings.'
1899   - print >> out, 'A full Python exception traceback follows.'
  1879 + sys.stderr.write('An error occurred while processing the following compiler settings.\n')
  1880 + sys.stderr.write('----------------------------------------------------------------------\n')
  1881 + sys.stderr.write('%s\n' % settingsStr.strip())
  1882 + sys.stderr.write('----------------------------------------------------------------------\n')
  1883 + sys.stderr.write('Please check the syntax of these settings.\n\n')
1900 1884 raise
1901 1885
1902 1886 def eatAttr(self):
2  cheetah/Template.py
@@ -1837,7 +1837,7 @@ def webInput(self, names, namesMulti=(), default='', src='f',
1837 1837 # 'dic = super(ThisClass, self).webInput(names, namesMulti, ...)'
1838 1838 # and then the code below.
1839 1839 if debug:
1840   - print "<PRE>\n" + pprint.pformat(dic) + "\n</PRE>\n\n"
  1840 + print("<PRE>\n" + pprint.pformat(dic) + "\n</PRE>\n\n")
1841 1841 self.searchList().insert(0, dic)
1842 1842 return dic
1843 1843
8 cheetah/TemplateCmdLineIface.py
@@ -41,7 +41,7 @@ def run(self):
41 41 """The main program controller."""
42 42
43 43 self._processCmdLineArgs()
44   - print self._template
  44 + print(self._template)
45 45
46 46 def _processCmdLineArgs(self):
47 47 try:
@@ -53,13 +53,13 @@ def _processCmdLineArgs(self):
53 53
54 54 except getopt.GetoptError, v:
55 55 # print help information and exit:
56   - print v
57   - print self.usage()
  56 + print(v)
  57 + print(self.usage())
58 58 sys.exit(2)
59 59
60 60 for o, a in self._opts:
61 61 if o in ('-h','--help'):
62   - print self.usage()
  62 + print(self.usage())
63 63 sys.exit()
64 64 if o == '--env':
65 65 self._template.searchList().insert(0, os.environ)
2  cheetah/Templates/_SkeletonPage.py
@@ -88,7 +88,7 @@ def stylesheetTags(self):
88 88 if not self._stylesheets.has_key(identifier):
89 89 warning = '# the identifier ' + identifier + \
90 90 'was in stylesheetsOrder, but not in stylesheets'
91   - print warning
  91 + print(warning)
92 92 stylesheetTagsTxt += warning
93 93 continue
94 94
4 cheetah/Tests/CheetahWrapper.py
@@ -52,7 +52,7 @@ class CFBase(unittest.TestCase):
52 52
53 53 def inform(self, message):
54 54 if self.verbose:
55   - print message
  55 + print(message)
56 56
57 57 def setUp(self):
58 58 """Create the top-level directories, subdirectories and .tmpl
@@ -520,7 +520,7 @@ def listTests(cheetahWrapperFile):
520 520 break
521 521 m = rx.search(lin)
522 522 if m:
523   - print m.group(1)
  523 + print(m.group(1))
524 524 f.close()
525 525
526 526 def main():
2  cheetah/Tests/Filters.py
@@ -31,7 +31,7 @@ def test_BasicHeader(self):
31 31 assert template == expected
32 32 except Exception, ex:
33 33 if ex.__class__.__name__ == 'MarkdownException' and majorVer == 2 and minorVer < 5:
34   - print '>>> NOTE: Support for the Markdown filter will be broken for you. Markdown says: %s' % ex
  34 + print('>>> NOTE: Support for the Markdown filter will be broken for you. Markdown says: %s' % ex)
35 35 return
36 36 raise
37 37
8 cheetah/Tests/Performance.py
@@ -57,8 +57,8 @@ def wrapper(*args, **kw):
57 57 pystone_total_time = total_time / pystone_rate
58 58 global DEBUG
59 59 if DEBUG:
60   - print 'The test "%s" took: %s pystones' % (function.func_name,
61   - pystone_total_time)
  60 + print('The test "%s" took: %s pystones' % (function.func_name,
  61 + pystone_total_time))
62 62 else:
63 63 if pystone_total_time > (max_num_pystones + TOLERANCE):
64 64 raise DurationError((('Test too long (%.2f Ps, '
@@ -98,8 +98,8 @@ def runTest(self):
98 98 self.prof.stop()
99 99 self.prof.close()
100 100 if self.display:
101   - print '>>> %s (%d iterations) ' % (self.__class__.__name__,
102   - self.iterations)
  101 + print('>>> %s (%d iterations) ' % (self.__class__.__name__,
  102 + self.iterations))
103 103 stats = hotshot.stats.load('%s.prof' % self.__class__.__name__)
104 104 #stats.strip_dirs()
105 105 stats.sort_stats('time', 'calls')
2  cheetah/Tests/Regressions.py
@@ -29,7 +29,7 @@ class GetAttrTest(unittest.TestCase):
29 29 def test_ValidException(self):
30 30 o = CustomGetAttrClass()
31 31 try:
32   - print o.attr
  32 + print(o.attr)
33 33 except GetAttrException, e:
34 34 # expected
35 35 return
2  cheetah/Tests/SyntaxAndOutput.py
@@ -171,7 +171,7 @@ def verify(self, input, expectedOutput,
171 171 )
172 172 moduleCode = templateObj._CHEETAH_generatedModuleCode
173 173 if self.DEBUGLEV >= 1:
174   - print moduleCode
  174 + print(moduleCode)
175 175 try:
176 176 output = templateObj.respond() # rather than __str__, because of unicode
177 177 assert output==expectedOutput, self._outputMismatchReport(output, expectedOutput)
4 cheetah/Tests/Template.py
@@ -293,7 +293,7 @@ def test_FailCase(self):
293 293 class ClassMethodSupport(TemplateTest):
294 294 def test_BasicDecorator(self):
295 295 if sys.version_info[0] == 2 and sys.version_info[1] == 3:
296   - print 'This version of Python doesn\'t support decorators, skipping tests'
  296 + print('This version of Python doesn\'t support decorators, skipping tests')
297 297 return
298 298 template = '''
299 299 #@classmethod
@@ -311,7 +311,7 @@ def test_BasicDecorator(self):
311 311 class StaticMethodSupport(TemplateTest):
312 312 def test_BasicDecorator(self):
313 313 if sys.version_info[0] == 2 and sys.version_info[1] == 3:
314   - print 'This version of Python doesn\'t support decorators, skipping tests'
  314 + print('This version of Python doesn\'t support decorators, skipping tests')
315 315 return
316 316 template = '''
317 317 #@staticmethod
4 cheetah/Tests/unittest_local_copy.py
@@ -917,8 +917,8 @@ def __init__(self, module='__main__', defaultTest=None,
917 917 self.runTests()
918 918
919 919 def usageExit(self, msg=None):
920   - if msg: print msg
921   - print self.USAGE % self.__dict__
  920 + if msg: print(msg)
  921 + print(self.USAGE % self.__dict__)
922 922 sys.exit(2)
923 923
924 924 def parseArgs(self, argv):
4 cheetah/Tests/xmlrunner.py
@@ -313,7 +313,7 @@ def test_stdout_capture(self):
313 313 """
314 314 class TestTest(unittest.TestCase):
315 315 def test_foo(self):
316   - print "Test"
  316 + print("Test")
317 317 self._try_test_run(TestTest, """<testsuite errors="0" failures="0" name="unittest.TestSuite" tests="1" time="0.000">
318 318 <testcase classname="__main__.TestTest" name="test_foo" time="0.000"></testcase>
319 319 <system-out><![CDATA[Test
@@ -329,7 +329,7 @@ def test_stderr_capture(self):
329 329 """
330 330 class TestTest(unittest.TestCase):
331 331 def test_foo(self):
332   - print >>sys.stderr, "Test"
  332 + sys.stderr.write('Test\n')
333 333 self._try_test_run(TestTest, """<testsuite errors="0" failures="0" name="unittest.TestSuite" tests="1" time="0.000">
334 334 <testcase classname="__main__.TestTest" name="test_foo" time="0.000"></testcase>
335 335 <system-out><![CDATA[]]></system-out>
10 cheetah/Tools/SiteHierarchy.py
@@ -173,10 +173,10 @@ def _inContents(self, contents):
173 173 ]
174 174
175 175 for url in ['/', '/services', '/services/products/widget', '/contact']:
176   - print '<p>', '='*50
177   - print '<br> %s: <br>\n' % url
  176 + print('<p>', '='*50)
  177 + print('<br> %s: <br>\n' % url)
178 178 n = Hierarchy(hierarchy, url, menuCSSClass='menu', crumbCSSClass='crumb',
179 179 prefix='/here')
180   - print n.menuList()
181   - print '<p>', '-'*50
182   - print n.crumbs()
  180 + print(n.menuList())
  181 + print('<p>', '-'*50)
  182 + print(n.crumbs())
39 cheetah/Utils/memcache.py
@@ -177,7 +177,6 @@ def _get_server(self, key):
177 177 for i in range(Client._SERVER_RETRIES):
178 178 server = self.buckets[serverhash % len(self.buckets)]
179 179 if server.connect():
180   - #print "(using server %s)" % server,
181 180 return server, key
182 181 serverhash = hash(str(serverhash) + str(i))
183 182 return None, None
@@ -555,10 +554,9 @@ def _doctest():
555 554 return doctest.testmod(memcache, globs=globs)
556 555
557 556 if __name__ == "__main__":
558   - print "Testing docstrings..."
  557 + print("Testing docstrings...")
559 558 _doctest()
560   - print "Running tests:"
561   - print
  559 + print("Running tests:")
562 560 #servers = ["127.0.0.1:11211", "127.0.0.1:11212"]
563 561 servers = ["127.0.0.1:11211"]
564 562 mc = Client(servers, debug=1)
@@ -568,14 +566,14 @@ def to_s(val):
568 566 return "%s (%s)" % (val, type(val))
569 567 return "%s" % val
570 568 def test_setget(key, val):
571   - print "Testing set/get {'%s': %s} ..." % (to_s(key), to_s(val)),
  569 + print("Testing set/get {'%s': %s} ..." % (to_s(key), to_s(val)))
572 570 mc.set(key, val)
573 571 newval = mc.get(key)
574 572 if newval == val:
575   - print "OK"
  573 + print("OK")
576 574 return 1
577 575 else:
578   - print "FAIL"
  576 + print("FAIL")
579 577 return 0
580 578
581 579 class FooStruct:
@@ -591,34 +589,33 @@ def __eq__(self, other):
591 589 test_setget("a_string", "some random string")
592 590 test_setget("an_integer", 42)
593 591 if test_setget("long", long(1<<30)):
594   - print "Testing delete ...",
  592 + print("Testing delete ...")
595 593 if mc.delete("long"):
596   - print "OK"
  594 + print("OK")
597 595 else:
598   - print "FAIL"
599   - print "Testing get_multi ...",
600   - print mc.get_multi(["a_string", "an_integer"])
  596 + print("FAIL")
  597 + print("Testing get_multi ...")
  598 + print(mc.get_multi(["a_string", "an_integer"]))
601 599
602   - print "Testing get(unknown value) ...",
603   - print to_s(mc.get("unknown_value"))
  600 + print("Testing get(unknown value) ...")
  601 + print(to_s(mc.get("unknown_value")))
604 602
605 603 f = FooStruct()
606 604 test_setget("foostruct", f)
607 605
608   - print "Testing incr ...",
  606 + print("Testing incr ...")
609 607 x = mc.incr("an_integer", 1)
610 608 if x == 43:
611   - print "OK"
  609 + print("OK")
612 610 else:
613   - print "FAIL"
  611 + print("FAIL")
614 612
615   - print "Testing decr ...",
  613 + print("Testing decr ...")
616 614 x = mc.decr("an_integer", 1)
617 615 if x == 42:
618   - print "OK"
  616 + print("OK")
619 617 else:
620   - print "FAIL"
621   -
  618 + print("FAIL")
622 619
623 620
624 621 # vim: ts=4 sw=4 et :
16 cheetah/Utils/statprof.py
@@ -277,15 +277,15 @@ def __init__(self, call_data):
277 277 self.cum_secs_per_call = None
278 278
279 279 def display(self):
280   - print '%6.2f %9.2f %9.2f %s' % (self.pcnt_time_in_proc,
  280 + print('%6.2f %9.2f %9.2f %s' % (self.pcnt_time_in_proc,
281 281 self.cum_secs_in_proc,
282 282 self.self_secs_in_proc,
283   - self.name)
  283 + self.name))
284 284
285 285
286 286 def display():
287 287 if state.sample_count == 0:
288   - print 'No samples recorded.'
  288 + print('No samples recorded.')
289 289 return
290 290
291 291 l = [CallStats(x) for x in call_data.itervalues()]
@@ -293,12 +293,12 @@ def display():
293 293 l.sort(reverse=True)
294 294 l = [x[2] for x in l]
295 295
296   - print '%5.5s %10.10s %7.7s %-8.8s' % ('% ', 'cumulative', 'self', '')
297   - print '%5.5s %9.9s %8.8s %-8.8s' % ("time", "seconds", "seconds", "name")
  296 + print('%5.5s %10.10s %7.7s %-8.8s' % ('% ', 'cumulative', 'self', ''))
  297 + print('%5.5s %9.9s %8.8s %-8.8s' % ("time", "seconds", "seconds", "name"))
298 298
299 299 for x in l:
300 300 x.display()
301 301
302   - print '---'
303   - print 'Sample count: %d' % state.sample_count
304   - print 'Total time: %f seconds' % state.accumulated_time
  302 + print('---')
  303 + print('Sample count: %d' % state.sample_count)
  304 + print('Total time: %f seconds' % state.accumulated_time)
10 cheetah/Version.py
@@ -32,11 +32,11 @@ def convertVersionStringToTuple(s):
32 32
33 33 if __name__ == '__main__':
34 34 c = convertVersionStringToTuple
35   - print c('2.0a1')
36   - print c('2.0b1')
37   - print c('2.0rc1')
38   - print c('2.0')
39   - print c('2.0.2')
  35 + print(c('2.0a1'))
  36 + print(c('2.0b1'))
  37 + print(c('2.0rc1'))
  38 + print(c('2.0'))
  39 + print(c('2.0.2'))
40 40
41 41
42 42 assert c('0.9.19b1') < c('0.9.19')

0 comments on commit 0b8c21f

Please sign in to comment.
Something went wrong with that request. Please try again.