[tor-commits] [tor/master] Use print() function in both Python 2 and Python 3

dgoulet at torproject.org dgoulet at torproject.org
Thu Jan 30 19:11:08 UTC 2020


commit 3208a74f906c116e93074c6ed0559df1cbfe58d1
Author: cclauss <cclauss at me.com>
Date:   Tue Jan 28 01:38:54 2020 +0100

    Use print() function in both Python 2 and Python 3
---
 contrib/client-tools/tor-resolve.py    | 10 +++++-----
 scripts/codegen/gen_server_ciphers.py  | 14 +++++++-------
 scripts/codegen/get_mozilla_ciphers.py |  8 ++++----
 scripts/codegen/makedesc.py            | 15 ++++++++++-----
 scripts/maint/format_changelog.py      |  2 +-
 scripts/maint/locatemissingdoxygen.py  |  6 +++---
 scripts/maint/redox.py                 | 17 +++++++++++------
 src/ext/ed25519/ref10/base.py          | 14 +++++++-------
 src/ext/ed25519/ref10/base2.py         | 10 +++++-----
 src/ext/ed25519/ref10/d.py             |  2 +-
 src/ext/ed25519/ref10/d2.py            |  2 +-
 src/ext/ed25519/ref10/sqrtm1.py        |  2 +-
 src/test/ed25519_exts_ref.py           | 20 ++++++++++----------
 13 files changed, 66 insertions(+), 56 deletions(-)

diff --git a/contrib/client-tools/tor-resolve.py b/contrib/client-tools/tor-resolve.py
index 593efc97d..356219371 100755
--- a/contrib/client-tools/tor-resolve.py
+++ b/contrib/client-tools/tor-resolve.py
@@ -87,7 +87,7 @@ def parseHostAndPort(h):
         try:
             port = int(h[i+1:])
         except ValueError:
-            print "Bad hostname %r"%h
+            print("Bad hostname %r"%h)
             sys.exit(1)
     elif h:
         try:
@@ -123,15 +123,15 @@ def resolve(hostname, sockshost, socksport, socksver=4, reverse=0):
             return None
         answer += more
         result = parse(answer)
-    print "Got answer",result
+    print("Got answer",result)
     m = s.recv(1)
     if m:
-        print "Got extra data too: %r"%m
+        print("Got extra data too: %r"%m)
     return result
 
 if __name__ == '__main__':
     if len(sys.argv) not in (2,3,4):
-        print "Syntax: resolve.py [-4|-5] hostname [sockshost:socksport]"
+        print("Syntax: resolve.py [-4|-5] hostname [sockshost:socksport]")
         sys.exit(0)
     socksver = 4
     reverse = 0
@@ -146,7 +146,7 @@ if __name__ == '__main__':
             break
 
     if len(sys.argv) >= 4:
-        print "Syntax: resolve.py [-x] [-4|-5] hostname [sockshost:socksport]"
+        print("Syntax: resolve.py [-x] [-4|-5] hostname [sockshost:socksport]")
         sys.exit(0)
     if len(sys.argv) == 3:
         sh,sp = parseHostAndPort(sys.argv[2])
diff --git a/scripts/codegen/gen_server_ciphers.py b/scripts/codegen/gen_server_ciphers.py
index dd295b7f7..3b7795224 100755
--- a/scripts/codegen/gen_server_ciphers.py
+++ b/scripts/codegen/gen_server_ciphers.py
@@ -101,7 +101,7 @@ def parse_cipher(ciph):
         fwsec, = m.groups()
         return Ciphersuite(ciph, fwsec, "CHACHA20", "256", "POLY1305", "n/a")
 
-    print "/* Couldn't parse %s ! */"%ciph
+    print("/* Couldn't parse %s ! */"%ciph)
     return None
 
 
@@ -125,12 +125,12 @@ for c in ALL_CIPHERS:
         colon = ' ":"'
 
     if c.name in MANDATORY:
-        print "%s/* Required */"%indent
-        print '%s%s%s'%(indent,c.name,colon)
+        print("%s/* Required */"%indent)
+        print('%s%s%s'%(indent,c.name,colon))
     else:
-        print "#ifdef %s"%c.name
-        print '%s%s%s'%(indent,c.name,colon)
-        print "#endif"
+        print("#ifdef %s"%c.name)
+        print('%s%s%s'%(indent,c.name,colon))
+        print("#endif")
 
-print '%s;'%indent
+print('%s;'%indent)
 
diff --git a/scripts/codegen/get_mozilla_ciphers.py b/scripts/codegen/get_mozilla_ciphers.py
index d149c71c2..165105736 100755
--- a/scripts/codegen/get_mozilla_ciphers.py
+++ b/scripts/codegen/get_mozilla_ciphers.py
@@ -20,7 +20,7 @@ import re
 import sys
 
 if len(sys.argv) != 3:
-    print >>sys.stderr, "Syntax: get_mozilla_ciphers.py <firefox-source-dir> <openssl-source-dir>"
+    print("Syntax: get_mozilla_ciphers.py <firefox-source-dir> <openssl-source-dir>", file=sys.stderr)
     sys.exit(1)
 
 ff_root = sys.argv[1]
@@ -176,13 +176,13 @@ for fl in oSSLinclude:
     fp.close()
 
 # Now generate the output.
-print """\
+print("""\
 /* This is an include file used to define the list of ciphers clients should
  * advertise.  Before including it, you should define the CIPHER and XCIPHER
  * macros.
  *
  * This file was automatically generated by get_mozilla_ciphers.py.
- */"""
+ */""")
 # Go in order by the order in CipherPrefs
 for firefox_macro in firefox_ciphers:
 
@@ -215,4 +215,4 @@ for firefox_macro in firefox_ciphers:
 #else
    XCIPHER(%(hex)s, %(macro)s)
 #endif""" % format
-    print res
+    print(res)
diff --git a/scripts/codegen/makedesc.py b/scripts/codegen/makedesc.py
index 7d8177f46..4c3cfdb07 100644
--- a/scripts/codegen/makedesc.py
+++ b/scripts/codegen/makedesc.py
@@ -30,6 +30,11 @@ import slow_ed25519
 import slownacl_curve25519
 import ed25519_exts_ref
 
+try:
+    xrange  # Python 2
+except NameError:
+    xrange = range  # Python 3
+
 # Pull in the openssl stuff we need.
 
 crypt = ctypes.CDLL(ctypes.util.find_library('crypto'))
@@ -303,10 +308,10 @@ def signdesc(body, args_out=None):
     return body.rstrip()
 
 def print_c_string(ident, body):
-    print "static const char %s[] =" % ident
+    print("static const char %s[] =" % ident)
     for line in body.split("\n"):
-        print '  "%s\\n"' %(line)
-    print "  ;"
+        print('  "%s\\n"' %(line))
+    print("  ;")
 
 def emit_ri(name, body):
     info = OnDemandKeys()
@@ -320,8 +325,8 @@ def emit_ei(name, body):
     body = info.sign_desc(body)
     print_c_string("EX_EI_%s"%name.upper(), body)
 
-    print 'const char EX_EI_{NAME}_FP[] = "{d.RSA_FINGERPRINT_NOSPACE}";'.format(
-        d=info, NAME=name.upper())
+    print('const char EX_EI_{NAME}_FP[] = "{d.RSA_FINGERPRINT_NOSPACE}";'.format(
+        d=info, NAME=name.upper()))
     print_c_string("EX_EI_%s_KEY"%name.upper(), info.RSA_IDENTITY)
 
 def analyze(s):
diff --git a/scripts/maint/format_changelog.py b/scripts/maint/format_changelog.py
index 5f04a44ef..32085c360 100755
--- a/scripts/maint/format_changelog.py
+++ b/scripts/maint/format_changelog.py
@@ -291,7 +291,7 @@ class ChangeLog(object):
             self.curgraf.append(line)
 
         else:
-            assert "This" is "unreachable"
+            assert "This" is "unreachable"  # noqa: F632
 
     def lint_head(self, line, head):
         m = re.match(r'^ *o ([^\(]+)((?:\([^\)]+\))?):', head)
diff --git a/scripts/maint/locatemissingdoxygen.py b/scripts/maint/locatemissingdoxygen.py
index 9e58bd347..773397735 100755
--- a/scripts/maint/locatemissingdoxygen.py
+++ b/scripts/maint/locatemissingdoxygen.py
@@ -34,10 +34,10 @@ def buildWarnings():
 
 def count(fn):
     if os.path.abspath(fn) not in warnings:
-        print "0\t%s"%fn
+        print("0\t%s"%fn)
     else:
         n = len(warnings[os.path.abspath(fn)])
-        print "%d\t%s"%(n,fn)
+        print("%d\t%s"%(n,fn))
 
 def getIndentation(line):
     s = line.lstrip()
@@ -67,7 +67,7 @@ def annotate(filename):
 
 if __name__ == '__main__':
     if len(sys.argv) == 1:
-        print "Usage: locatemissingdoxygen.py [-A] filename... <doxygen_log"
+        print("Usage: locatemissingdoxygen.py [-A] filename... <doxygen_log")
         sys.exit(1)
     buildWarnings()
     if sys.argv[1] == '-A':
diff --git a/scripts/maint/redox.py b/scripts/maint/redox.py
index 171c6d969..3ad3e3f1b 100755
--- a/scripts/maint/redox.py
+++ b/scripts/maint/redox.py
@@ -37,6 +37,11 @@ from __future__ import unicode_literals
 import re
 import sys
 
+try:
+    xrange  # Python 2
+except NameError:
+    xrange = range  # Python 3
+
 # Which files should we ignore warning from?  Mostly, these are external
 # files that we've snarfed in from somebody else, whose C we do no intend
 # to document for them.
@@ -78,7 +83,7 @@ def parsething(thing):
     else:
         m = THING_RE.match(thing)
         if not m:
-            print thing, "???? Format didn't match."
+            print(thing, "???? Format didn't match.")
             return None, None
         else:
             name, tp, parent = m.groups()
@@ -155,7 +160,7 @@ def checkf(fn, errs):
     """
     for skip in SKIP_FILES:
         if fn.endswith(skip):
-            print "Skipping",fn
+            print("Skipping",fn)
             return
 
     comments = []
@@ -174,8 +179,8 @@ def checkf(fn, errs):
 
         ln = findline(lines, line, name)
         if ln == None:
-            print "Couldn't find the definition of %s allegedly on %s of %s"%(
-                name, line, fn)
+            print("Couldn't find the definition of %s allegedly on %s of %s"%(
+                name, line, fn))
         else:
             if hasdocdoc(lines, line, kind):
 #                print "Has a DOCDOC"
@@ -220,12 +225,12 @@ def applyComments(fn, entries):
         outf.write(line)
     outf.close()
 
-    print "Added %s DOCDOCs to %s" %(N, fn)
+    print("Added %s DOCDOCs to %s" %(N, fn))
 
 e = read()
 
 for fn, errs in e.iteritems():
-    print `(fn, errs)`
+    print(repr((fn, errs)))
     comments = checkf(fn, errs)
     if comments:
         applyComments(fn, comments)
diff --git a/src/ext/ed25519/ref10/base.py b/src/ext/ed25519/ref10/base.py
index 8bfaab056..3d477c5c3 100644
--- a/src/ext/ed25519/ref10/base.py
+++ b/src/ext/ed25519/ref10/base.py
@@ -56,15 +56,15 @@ def radix255(x):
 
 Bi = B
 for i in range(32):
-  print "{"
+  print("{")
   Bij = Bi
   for j in range(8):
-    print " {"
-    print "  {",radix255(Bij[1]+Bij[0]),"},"
-    print "  {",radix255(Bij[1]-Bij[0]),"},"
-    print "  {",radix255(2*d*Bij[0]*Bij[1]),"},"
+    print(" {")
+    print("  {",radix255(Bij[1]+Bij[0]),"},")
+    print("  {",radix255(Bij[1]-Bij[0]),"},")
+    print("  {",radix255(2*d*Bij[0]*Bij[1]),"},")
     Bij = edwards(Bij,Bi)
-    print " },"
-  print "},"
+    print(" },")
+  print("},")
   for k in range(8):
     Bi = edwards(Bi,Bi)
diff --git a/src/ext/ed25519/ref10/base2.py b/src/ext/ed25519/ref10/base2.py
index 5923e43a7..3f8e3d25d 100644
--- a/src/ext/ed25519/ref10/base2.py
+++ b/src/ext/ed25519/ref10/base2.py
@@ -57,9 +57,9 @@ def radix255(x):
 Bi = B
 
 for i in range(8):
-  print " {"
-  print "  {",radix255(Bi[1]+Bi[0]),"},"
-  print "  {",radix255(Bi[1]-Bi[0]),"},"
-  print "  {",radix255(2*d*Bi[0]*Bi[1]),"},"
-  print " },"
+  print(" {")
+  print("  {",radix255(Bi[1]+Bi[0]),"},")
+  print("  {",radix255(Bi[1]-Bi[0]),"},")
+  print("  {",radix255(2*d*Bi[0]*Bi[1]),"},")
+  print(" },")
   Bi = edwards(B,edwards(B,Bi))
diff --git a/src/ext/ed25519/ref10/d.py b/src/ext/ed25519/ref10/d.py
index 3fbb17507..5b875de66 100644
--- a/src/ext/ed25519/ref10/d.py
+++ b/src/ext/ed25519/ref10/d.py
@@ -30,4 +30,4 @@ def radix255(x):
   return result
 
 d = -121665 * inv(121666)
-print radix255(d)
+print(radix255(d))
diff --git a/src/ext/ed25519/ref10/d2.py b/src/ext/ed25519/ref10/d2.py
index 3e533730b..f59a1bc62 100644
--- a/src/ext/ed25519/ref10/d2.py
+++ b/src/ext/ed25519/ref10/d2.py
@@ -30,4 +30,4 @@ def radix255(x):
   return result
 
 d = -121665 * inv(121666)
-print radix255(d*2)
+print(radix255(d*2))
diff --git a/src/ext/ed25519/ref10/sqrtm1.py b/src/ext/ed25519/ref10/sqrtm1.py
index a276d4e67..df9f26ee1 100644
--- a/src/ext/ed25519/ref10/sqrtm1.py
+++ b/src/ext/ed25519/ref10/sqrtm1.py
@@ -30,4 +30,4 @@ def radix255(x):
   return result
 
 I = expmod(2,(q-1)/4,q)
-print radix255(I)
+print(radix255(I))
diff --git a/src/test/ed25519_exts_ref.py b/src/test/ed25519_exts_ref.py
index 658f7cde1..ae537ff15 100644
--- a/src/test/ed25519_exts_ref.py
+++ b/src/test/ed25519_exts_ref.py
@@ -152,7 +152,7 @@ class SelfTest(unittest.TestCase):
         # Check that identities match
         assert(identity == identity2)
         # Check that identity is the point (0,1)
-        assert(identity == [0L,1L])
+        assert(identity == [0,1])
 
         # Check identity element: a*E = E, where a is a random scalar
         scalar = random_scalar(os.urandom)
@@ -186,22 +186,22 @@ BLINDING_PARAMS = [
 PREFIX = "ED25519_"
 
 def writeArray(name, array):
-    print "static const char *{prefix}{name}[] = {{".format(
-        prefix=PREFIX,name=name)
+    print("static const char *{prefix}{name}[] = {{".format(
+        prefix=PREFIX,name=name))
     for a in array:
         h = binascii.b2a_hex(a)
         if len(h) > 70:
             h1 = h[:70]
             h2 = h[70:]
-            print '  "{0}"\n      "{1}",'.format(h1,h2)
+            print('  "{0}"\n      "{1}",'.format(h1,h2))
         else:
-            print '  "{0}",'.format(h)
-    print "};\n"
+            print('  "{0}",'.format(h))
+    print("};\n")
 
 def comment(text, initial="/**"):
-    print initial
-    print textwrap.fill(text,initial_indent=" * ",subsequent_indent=" * ")
-    print " */"
+    print(initial)
+    print(textwrap.fill(text,initial_indent=" * ",subsequent_indent=" * "))
+    print(" */")
 
 def makeTestVectors():
     comment("""Test vectors for our ed25519 implementation and related
@@ -257,7 +257,7 @@ def makeTestVectors():
 if __name__ == '__main__':
     import sys
     if len(sys.argv) == 1 or sys.argv[1] not in ("SelfTest", "MakeVectors"):
-        print "You should specify one of 'SelfTest' or 'MakeVectors'"
+        print("You should specify one of 'SelfTest' or 'MakeVectors'")
         sys.exit(1)
     if sys.argv[1] == 'SelfTest':
         unittest.main()





More information about the tor-commits mailing list