[llvm-dev] Python version for scripts in LLVM?

Craig Rodrigues via llvm-dev llvm-dev at lists.llvm.org
Fri Oct 9 15:33:31 PDT 2015


Hi,

Is there a rule or guideline about what Python versions
must be supported for scripts in the LLVM tree?

I am working on some patches to some scripts in LLVM
to use features in Python 2.7, so that these scripts
can run under Python 2.7 and Python 3.x

Is that OK?

For example, here is a patch to use print as a function,
so that the scripts can work in Python 2.7 and Python 3.x
--
Craig
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-dev/attachments/20151009/dbb54b3a/attachment.html>
-------------- next part --------------
Index: DSAclean.py
===================================================================
--- DSAclean.py	(revision 249819)
+++ DSAclean.py	(working copy)
@@ -1,5 +1,7 @@
 #! /usr/bin/python
 
+from __future__ import print_function
+
 #changelog: 
 #10/13/2005b: replaced the # in tmp(.#*)* with alphanumeric and _, this will then remove
 #nodes such as %tmp.1.i and %tmp._i.3
@@ -11,7 +13,7 @@
 import re
 import sys
 if( len(sys.argv) < 3 ):
-	print 'usage is: ./DSAclean <dot_file_to_be_cleaned> <out_put_file>'
+	print('usage is: ./DSAclean <dot_file_to_be_cleaned> <out_put_file>')
 	sys.exit(1)
 #get a file object
 input = open(sys.argv[1], 'r')
Index: DSAextract.py
===================================================================
--- DSAextract.py	(revision 249819)
+++ DSAextract.py	(working copy)
@@ -1,5 +1,7 @@
 #! /usr/bin/python
 
+from __future__ import print_function
+
 #this is a script to extract given named nodes from a dot file, with
 #the associated edges.  An edge is kept iff for edge x -> y
 # x and y are both nodes specified to be kept.
@@ -31,8 +33,8 @@
 
 
 if len(sys.argv) < 3:
-	print 'usage is ./DSAextract <dot_file_to_modify> \
-			<output_file> [list of nodes to extract]'
+	print('usage is ./DSAextract <dot_file_to_modify> \
+			<output_file> [list of nodes to extract]')
 
 #open the input file
 input = open(sys.argv[1], 'r')
@@ -71,11 +73,11 @@
 
 
 #test code
-#print '\n'
+#print('\n')
 
-print node_name_set
+print(node_name_set)
 
-#print node_set
+#print(node_set)
 	
 
 #open the output file
Index: bisect
===================================================================
--- bisect	(revision 249819)
+++ bisect	(working copy)
@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 
+from __future__ import print_function
 import os
 import sys
 import argparse
@@ -25,7 +26,7 @@
     count = start + (end - start)/2
     print("Visiting Count: %d with (Start, End) = (%d,%d)" % (count, start, end))
     cmd = [x % {'count':count} for x in args.command]
-    print cmd
+    print(cmd)
     result = subprocess.call(cmd)
     if result == 0:
         print("    PASSES! Setting start to count")
Index: create_ladder_graph.py
===================================================================
--- create_ladder_graph.py	(revision 249819)
+++ create_ladder_graph.py	(working copy)
@@ -10,6 +10,7 @@
 really behaving linearly.
 """
 
+from __future__ import print_function
 import argparse
 def main():
   parser = argparse.ArgumentParser(description=__doc__)
@@ -17,27 +18,27 @@
                       help="Number of ladder rungs. Must be a multiple of 2")
   args = parser.parse_args()
   if (args.rungs % 2) != 0:
-    print "Rungs must be a multiple of 2"
+    print("Rungs must be a multiple of 2")
     return
-  print "int ladder(int *foo, int *bar, int x) {"
+  print("int ladder(int *foo, int *bar, int x) {")
   rung1 = xrange(0, args.rungs, 2)
   rung2 = xrange(1, args.rungs, 2)
   for i in rung1:
-    print "rung1%d:" % i
-    print "*foo = x++;"
+    print("rung1%d:" % i)
+    print("*foo = x++;")
     if i != rung1[-1]:
-      print "if (*bar) goto rung1%d;" % (i+2)
-      print "else goto rung2%d;" % (i+1)
+      print("if (*bar) goto rung1%d;" % (i+2))
+      print("else goto rung2%d;" % (i+1))
     else:
-      print "goto rung2%d;" % (i+1)
+      print("goto rung2%d;" % (i+1))
   for i in rung2:
-    print "rung2%d:" % i
-    print "*foo = x++;"
+    print("rung2%d:" % i)
+    print("*foo = x++;")
     if i != rung2[-1]:
-      print "goto rung2%d;" % (i+2)
+      print("goto rung2%d;" % (i+2))
     else:
-      print "return *foo;"
-  print "}"
+      print("return *foo;")
+  print("}")
 
 if __name__ == '__main__':
   main()
Index: lint/common_lint.py
===================================================================
--- lint/common_lint.py	(revision 249819)
+++ lint/common_lint.py	(working copy)
@@ -2,6 +2,7 @@
 #
 # Common lint functions applicable to multiple types of files.
 
+from __future__ import print_function
 import re
 
 def VerifyLineLength(filename, lines, max_length):
@@ -89,7 +90,7 @@
   for filename in filenames:
     file = open(filename, 'r')
     if not file:
-      print 'Cound not open %s' % filename
+      print('Cound not open %s' % filename)
       continue
     lines = file.readlines()
     lint.extend(linter.RunOnFile(filename, lines))
Index: lint/cpp_lint.py
===================================================================
--- lint/cpp_lint.py	(revision 249819)
+++ lint/cpp_lint.py	(working copy)
@@ -6,6 +6,7 @@
 # TODO: add unittests for the verifier functions:
 # http://docs.python.org/library/unittest.html .
 
+from __future__ import print_function
 import common_lint
 import re
 import sys
@@ -86,7 +87,7 @@
 def CppLintMain(filenames):
   all_lint = common_lint.RunLintOverAllFiles(CppLint(), filenames)
   for lint in all_lint:
-    print '%s:%d:%s' % (lint[0], lint[1], lint[2])
+    print('%s:%d:%s' % (lint[0], lint[1], lint[2]))
   return 0
 
 
Index: shuffle_fuzz.py
===================================================================
--- shuffle_fuzz.py	(revision 249819)
+++ shuffle_fuzz.py	(working copy)
@@ -13,6 +13,7 @@
 a bug.
 """
 
+from __future__ import print_function
 import argparse
 import itertools
 import random
@@ -109,13 +110,13 @@
 
   if args.verbose:
     # Print out the shuffle sequence in a compact form.
-    print >>sys.stderr, ('Testing shuffle sequence "%s" (v%d%s):' %
-                         (args.seed, width, element_type))
+    print ('Testing shuffle sequence "%s" (v%d%s):' %
+           (args.seed, width, element_type), file=sys.stderr)
     for i, shuffles in enumerate(shuffle_tree):
-      print >>sys.stderr, '  tree level %d:' % (i,)
+      print('  tree level %d:' % (i,), file=sys.stderr)
       for j, s in enumerate(shuffles):
-        print >>sys.stderr, '    shuffle %d: %s' % (j, s)
-    print >>sys.stderr, ''
+        print('    shuffle %d: %s' % (j, s), file=sys.stderr)
+    print('', file=sys.stderr)
 
   # Symbolically evaluate the shuffle tree.
   inputs = [[int(j % element_modulus)
@@ -128,7 +129,7 @@
                 for j in s]
                for i, s in enumerate(shuffles)]
   if len(results) != 1:
-    print >>sys.stderr, 'ERROR: Bad results: %s' % (results,)
+    print('ERROR: Bad results: %s' % (results,), file=sys.stderr)
     sys.exit(1)
   result = results[0]
 
Index: update_llc_test_checks.py
===================================================================
--- update_llc_test_checks.py	(revision 249819)
+++ update_llc_test_checks.py	(working copy)
@@ -6,7 +6,7 @@
 FileCheck patterns. It can either update all of the tests in the file or
 a single test function.
 """
-
+from __future__ import print_function
 import argparse
 import itertools
 import string
@@ -76,7 +76,7 @@
 
   for test in args.tests:
     if args.verbose:
-      print >>sys.stderr, 'Scanning for RUN lines in test file: %s' % (test,)
+      print('Scanning for RUN lines in test file: %s' % (test,), file=sys.stderr)
     with open(test) as f:
       test_lines = [l.rstrip() for l in f]
 
@@ -83,19 +83,19 @@
     run_lines = [m.group(1)
                  for m in [run_line_re.match(l) for l in test_lines] if m]
     if args.verbose:
-      print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),)
+      print('Found %d RUN lines:' % (len(run_lines),), file=sys.stderr)
       for l in run_lines:
-        print >>sys.stderr, '  RUN: ' + l
+        print('  RUN: ' + l, file=sys.stderr)
 
     checks = []
     for l in run_lines:
       (llc_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
       if not llc_cmd.startswith('llc '):
-        print >>sys.stderr, 'WARNING: Skipping non-llc RUN line: ' + l
+        print('WARNING: Skipping non-llc RUN line: ' + l, file=sys.stderr)
         continue
 
       if not filecheck_cmd.startswith('FileCheck '):
-        print >>sys.stderr, 'WARNING: Skipping non-FileChecked RUN line: ' + l
+        print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
         continue
 
       llc_cmd_args = llc_cmd[len('llc'):].strip()
@@ -116,8 +116,8 @@
         asm.update({prefix: dict()})
     for prefixes, llc_args in checks:
       if args.verbose:
-        print >>sys.stderr, 'Extracted LLC cmd: llc ' + llc_args
-        print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes)
+        print('Extracted LLC cmd: llc ' + llc_args, file=sys.stderr)
+        print('Extracted FileCheck prefixes: ' + str(prefixes), file=sys.stderr)
       raw_asm = llc(args, llc_args, test)
       # Build up a dictionary of all the function bodies.
       for m in asm_function_re.finditer(raw_asm):
@@ -129,14 +129,14 @@
           # We only use the last line of the asm for stress tests.
           f_asm = '\n'.join(f_asm.splitlines()[-1:])
         if args.verbose:
-          print >>sys.stderr, 'Processing asm for function: ' + f
+          print('Processing asm for function: ' + f, file=sys.stderr)
           for l in f_asm.splitlines():
-            print >>sys.stderr, '  ' + l
+            print('  ' + l, file=sys.stderr)
         for prefix in prefixes:
           if f in asm[prefix] and asm[prefix][f] != f_asm:
             if prefix == prefixes[-1]:
-              print >>sys.stderr, ('WARNING: Found conflicting asm under the '
-                                   'same prefix!')
+              print('WARNING: Found conflicting asm under the '
+                                   'same prefix!', file=sys.stderr)
             else:
               asm[prefix][f] = None
               continue
@@ -147,7 +147,7 @@
     is_in_function_start = False
     prefix_set = set([prefix for prefixes, _ in checks for prefix in prefixes])
     if args.verbose:
-      print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,)
+      print('Rewriting FileCheck prefixes: %s' % (prefix_set,), file=sys.stderr)
     fixed_lines = []
     for l in test_lines:
       if is_in_function_start:
Index: wciia.py
===================================================================
--- wciia.py	(revision 249819)
+++ wciia.py	(working copy)
@@ -20,6 +20,7 @@
 
 """
 
+from __future__ import print_function
 import os
 
 code_owners = {}
@@ -42,7 +43,7 @@
 	if 'filesfolders' in owner:
 		filesfolders = owner['filesfolders']
 	else:
-#		print "F: field missing, using D: field"
+#		print("F: field missing, using D: field")
 		owner['filesfolders'] = owner['description']
 	process_files_and_folders(owner)
 	code_owners[owner['name']] = owner
@@ -77,7 +78,7 @@
 		owner = code_owners[name]
 		if 'paths' in owner:
 			for path in owner['paths']:
-#				print "searching (" + path + ")"
+#				print("searching (" + path + ")")
 				# try exact match
 				if fpath == path:
 					return name
@@ -97,7 +98,7 @@
 import sys
 
 if len(sys.argv) < 2:
-	print "usage " + sys.argv[0] + " file_or_folder"  
+	print("usage " + sys.argv[0] + " file_or_folder")
 	exit(-1)
 	
 # the path we are checking
@@ -105,13 +106,13 @@
 
 # check if this is real path
 if not os.path.exists(path):
-	print "path (" + path + ") does not exist"
+	print("path (" + path + ") does not exist")
 	exit(-1)
 	
 owners_name = find_owners(path)
 
 # be grammatically correct
-print "The owner(s) of the (" + path + ") is(are) : " + str(owners_name)
+print("The owner(s) of the (" + path + ") is(are) : " + str(owners_name))
 
 exit(0)
 
@@ -119,7 +120,7 @@
 # not yet used 
 root = "."
 for dir,subdirList,fileList in os.walk( root , topdown=False ) :
-   print "dir :" , dir
+   print("dir :" , dir)
    for fname in fileList :
-      print "-" , fname
-   print
+      print("-" , fname)
+   print()


More information about the llvm-dev mailing list