Python3 updates for print() and tab/spaces
authorTom Henderson <tomh@tomh.org>
Thu, 03 Sep 2015 18:28:56 -0700
changeset 58 74b94ecd0120
parent 57 5c203d28a3d1
child 59 bd918e1a85dc
Python3 updates for print() and tab/spaces
build.py
dist.py
download.py
util.py
--- a/build.py	Sun Jul 26 14:02:12 2015 +0100
+++ b/build.py	Thu Sep 03 18:28:56 2015 -0700
@@ -1,4 +1,5 @@
 #! /usr/bin/env python
+from __future__ import print_function
 import sys
 from optparse import OptionParser
 import os
@@ -13,40 +14,40 @@
     qmake = 'qmake'
     qmakeFound = False
     try:
-	run_command([qmake, '-v'])
-	print "qmake found"
-	qmakeFound = True
+        run_command([qmake, '-v'])
+        print("qmake found")
+        qmakeFound = True
     except:
-	print "Could not find qmake in the default path"
+        print("Could not find qmake in the default path")
 
     try:
-	if qmakeFound == False:
-		run_command(['qmake-qt4', '-v'])
-		qmake = 'qmake-qt4'
-		print "qmake-qt4 found"
+        if qmakeFound == False:
+                run_command(['qmake-qt4', '-v'])
+                qmake = 'qmake-qt4'
+                print("qmake-qt4 found")
     except:
-	print "Could not find qmake-qt4 in the default path"
-	
+        print("Could not find qmake-qt4 in the default path")
+        
     if qmakepath:
-	print "Setting qmake to user provided path"
+        print("Setting qmake to user provided path")
         qmake = qmakepath
     try:    
-    	if sys.platform in ['darwin']:
-    		run_command([qmake, '-spec', 'macx-g++', 'NetAnim.pro'])
-    	else:
-    		run_command([qmake, 'NetAnim.pro'])
-    	run_command(['make'])
+        if sys.platform in ['darwin']:
+            run_command([qmake, '-spec', 'macx-g++', 'NetAnim.pro'])
+        else:
+            run_command([qmake, 'NetAnim.pro'])
+        run_command(['make'])
     except OSError:
-        print "Error building NetAnim. Ensure the path to qmake is correct."
-        print "Could not find qmake or qmake-qt4 in the default PATH."
-        print "Use ./build.py --qmake-path <Path-to-qmake>, if qmake is installed in a non-standard location"
-        print "Note: Some systems use qmake-qt4 instead of qmake"
-        print "Skipping NetAnim ...."
-	pass
+        print("Error building NetAnim. Ensure the path to qmake is correct.")
+        print("Could not find qmake or qmake-qt4 in the default PATH.")
+        print("Use ./build.py --qmake-path <Path-to-qmake>, if qmake is installed in a non-standard location")
+        print("Note: Some systems use qmake-qt4 instead of qmake")
+        print("Skipping NetAnim ....")
+        pass
     except:
-        print "Error building NetAnim."
-        print "Skipping NetAnim ...."
-	pass
+        print("Error building NetAnim.")
+        print("Skipping NetAnim ....")
+        pass
 
 def build_ns3(config, build_examples, build_tests, args, build_options):
     cmd = [sys.executable, "waf", "configure"] + args
@@ -71,7 +72,7 @@
     try:
         pybindgen, = config.getElementsByTagName("pybindgen")
     except ValueError:
-        print "Note: configuring ns-3 without pybindgen"
+        print("Note: configuring ns-3 without pybindgen")
     else:
         cmd.extend([
                 "--with-pybindgen", os.path.join("..", pybindgen.getAttribute("dir")),
@@ -105,44 +106,44 @@
     try:
         dot_config = open(".config", "rt")
     except IOError:
-        print >> sys.stderr, "** ERROR: missing .config file; you probably need to run the download.py script first."
+        print("** ERROR: missing .config file; you probably need to run the download.py script first.", file=sys.stderr)
         sys.exit(2)
 
     config = dom.parse(dot_config)
     dot_config.close()
 
     if options.disable_netanim:
-        print "# Skip NetAnimC (by user request)"
+        print("# Skip NetAnimC (by user request)")
         for node in config.getElementsByTagName("netanim"):
             config.documentElement.removeChild(node)
     elif sys.platform in ['cygwin', 'win32']:
-        print "# Skip NetAnim (platform not supported)"
+        print("# Skip NetAnim (platform not supported)")
     else:
         netanim_config_elems = config.getElementsByTagName("netanim")
         if netanim_config_elems:
             netanim_config, = netanim_config_elems
             netanim_dir = netanim_config.getAttribute("dir")
-            print "# Build NetAnim"
+            print("# Build NetAnim")
             os.chdir(netanim_dir)
-            print "Entering directory `%s'" % netanim_dir
+            print("Entering directory `%s'" % netanim_dir)
             try:
                 try:
                     build_netanim(options.qmake_path)
                 except CommandError:
-                    print "# Build NetAnim: failure (ignoring NetAnim)"
+                    print("# Build NetAnim: failure (ignoring NetAnim)")
                     config.documentElement.removeChild(netanim_config)
             finally:
                 os.chdir(cwd)
-            print "Leaving directory `%s'" % netanim_dir
+            print("Leaving directory `%s'" % netanim_dir)
 
     if options.enable_examples:
-        print "# Building examples (by user request)"
+        print("# Building examples (by user request)")
         build_examples = True
     else:
         build_examples = False
 
     if options.enable_tests:
-        print "# Building tests (by user request)"
+        print("# Building tests (by user request)")
         build_tests = True
     else:
         build_tests = False
@@ -152,16 +153,16 @@
     else:
         build_options = shlex.split(options.build_options)
 
-    print "# Build NS-3"
+    print("# Build NS-3")
     ns3_config, = config.getElementsByTagName("ns-3")
     d = os.path.join(os.path.dirname(__file__), ns3_config.getAttribute("dir"))
-    print "Entering directory `%s'" % d
+    print("Entering directory `%s'" % d)
     os.chdir(d)
     try:
         build_ns3(config, build_examples, build_tests, args, build_options)
     finally:
         os.chdir(cwd)
-    print "Leaving directory `%s'" % d
+    print("Leaving directory `%s'" % d)
 
 
     return 0
--- a/dist.py	Sun Jul 26 14:02:12 2015 +0100
+++ b/dist.py	Thu Sep 03 18:28:56 2015 -0700
@@ -1,4 +1,5 @@
 #! /usr/bin/env python
+from __future__ import print_function
 import sys
 from optparse import OptionParser
 import os
@@ -37,7 +38,7 @@
                 continue
             srcpath = os.path.join(dirpath, filename)
             tgtpath = os.path.join(tgtdir, reldirpath, filename)
-            #print srcpath, "=>", tgtpath
+            #print(srcpath, "=>", tgtpath)
             tar.add(srcpath, tgtpath)
             
 
@@ -52,7 +53,7 @@
     try:
         dot_config = open(".config", "rt")
     except IOError:
-        print >> sys.stderr, "** ERROR: missing .config file; you probably need to run the download.py script first."
+        print("** ERROR: missing .config file; you probably need to run the download.py script first.", file=sys.stderr)
         sys.exit(2)
 
     config = dom.parse(dot_config)
@@ -62,7 +63,7 @@
     ns3_dir = ns3_config.getAttribute("dir")
     ns3_version = open(os.path.join(ns3_dir, "VERSION"), "rt").readline().strip()
     
-    print "NS-3 version: %r" % (ns3_version,)
+    print("NS-3 version: %r" % (ns3_version,))
     dist_dir = "ns-allinone-%s" % ns3_version
     arch_name = "%s.tar.bz2" % dist_dir
 
@@ -95,7 +96,7 @@
         if filename.endswith('~'):
             return True
         return False
-    print "Adding %s as %s" % (ns3_dir, os.path.join(dist_dir, new_ns3_dir))
+    print("Adding %s as %s" % (ns3_dir, os.path.join(dist_dir, new_ns3_dir)))
     tar_add_tree(tar, ns3_dir, os.path.join(dist_dir, new_ns3_dir), dir_excl, file_excl)
 
     # add pybindgen
@@ -116,7 +117,7 @@
         if filename.endswith('~'):
             return True
         return False
-    print "Adding %s as %s" % (pybindgen_dir, os.path.join(dist_dir, new_pybindgen_dir))
+    print("Adding %s as %s" % (pybindgen_dir, os.path.join(dist_dir, new_pybindgen_dir)))
     tar_add_tree(tar, pybindgen_dir, os.path.join(dist_dir, new_pybindgen_dir), dir_excl, file_excl)
 
     # add NetAnim
@@ -134,7 +135,7 @@
         if filename.endswith('~'):
             return True
         return False
-    print "Adding %s as %s" % (netanim_dir, os.path.join(dist_dir, new_netanim_dir))
+    print("Adding %s as %s" % (netanim_dir, os.path.join(dist_dir, new_netanim_dir)))
     tar_add_tree(tar, netanim_dir, os.path.join(dist_dir, new_netanim_dir), dir_excl, file_excl)
 
     # add bake
@@ -152,11 +153,11 @@
         if filename.endswith('~'):
             return True
         return False
-    print "Adding %s as %s" % (bake_dir, os.path.join(dist_dir, new_bake_dir))
+    print("Adding %s as %s" % (bake_dir, os.path.join(dist_dir, new_bake_dir)))
     tar_add_tree(tar, bake_dir, os.path.join(dist_dir, new_bake_dir), dir_excl, file_excl)
 
     # add the build script files
-    print "Adding the build script files"
+    print("Adding the build script files")
     for filename in ["build.py", "constants.py", "util.py", "README"]:
         tar.add(filename, os.path.join(dist_dir, filename))
 
@@ -166,7 +167,7 @@
     new_config.writexml(new_config_file)
     tarinfo = tarfile.TarInfo(os.path.join(dist_dir, ".config"))
     tarinfo.mtime = time.time()
-    tarinfo.mode = 0644
+    tarinfo.mode = 0o644
     tarinfo.type = tarfile.REGTYPE
     tarinfo.size = new_config_file.tell()
     new_config_file.seek(0)
--- a/download.py	Sun Jul 26 14:02:12 2015 +0100
+++ b/download.py	Thu Sep 03 18:28:56 2015 -0700
@@ -1,4 +1,5 @@
 #! /usr/bin/env python
+from __future__ import print_function
 import sys
 from optparse import OptionParser
 import os
@@ -12,33 +13,33 @@
 
 
 def get_ns3(ns3_branch):
-    print """
+    print("""
     #
     # Get NS-3
     #
-    """
+    """)
     ns3_dir = os.path.split(ns3_branch)[-1]
     ns3_branch_url = constants.NSNAM_CODE_BASE_URL + ns3_branch
 
     if not os.path.exists(ns3_dir):
-        print "Cloning ns-3 branch"
+        print("Cloning ns-3 branch")
         run_command(['hg', 'clone', ns3_branch_url, ns3_dir])
     else:
-        print "Updating ns-3 branch"
+        print("Updating ns-3 branch")
         run_command(['hg', '--cwd', ns3_dir, 'pull', '-u'])
 
     return ns3_dir
 
 
 def get_pybindgen(ns3_dir):
-    print """
+    print("""
     #
     # Get PyBindGen
     #
-    """
+    """)
 
     if sys.platform in ['cygwin']:
-        print "Architecture (%s) does not support PyBindGen ... skipping" % (sys.platform,)
+        print("Architecture (%s) does not support PyBindGen ... skipping" % (sys.platform,))
         raise RuntimeError
 
     # (peek into the ns-3 wscript and extract the required pybindgen version)
@@ -51,7 +52,7 @@
             break
     if required_pybindgen_version is None:
         fatal("Unable to detect pybindgen required version")
-    print "Required pybindgen version: ", required_pybindgen_version
+    print("Required pybindgen version: ", required_pybindgen_version)
 
     # work around http_proxy handling bug in bzr
     # if 'http_proxy' in os.environ and 'https_proxy' not in os.environ:
@@ -65,25 +66,25 @@
         rev = required_pybindgen_version
 
     if os.path.exists(constants.LOCAL_PYBINDGEN_PATH):
-        print "Trying to update pybindgen; this will fail if no network connection is available.  Hit Ctrl-C to skip."
+        print("Trying to update pybindgen; this will fail if no network connection is available.  Hit Ctrl-C to skip.")
 
         try:
             run_command(["git", "fetch", constants.PYBINDGEN_BRANCH],
                         cwd=constants.LOCAL_PYBINDGEN_PATH)
         except KeyboardInterrupt:
-            print "Interrupted; Python bindings will be disabled."
+            print("Interrupted; Python bindings will be disabled.")
         else:
-            print "Update was successful."
+            print("Update was successful.")
     else:
-        print "Trying to fetch pybindgen; this will fail if no network connection is available.  Hit Ctrl-C to skip."
+        print("Trying to fetch pybindgen; this will fail if no network connection is available.  Hit Ctrl-C to skip.")
         try:
             run_command(["git", "clone", constants.PYBINDGEN_BRANCH,
                         constants.LOCAL_PYBINDGEN_PATH])
         except KeyboardInterrupt:
-            print "Interrupted; Python bindings will be disabled."
+            print("Interrupted; Python bindings will be disabled.")
             shutil.rmtree(constants.LOCAL_PYBINDGEN_PATH, True)
             return False
-        print "Fetch was successful."
+        print("Fetch was successful.")
 
     run_command(["git", "checkout", rev, "-q"],
                 cwd=constants.LOCAL_PYBINDGEN_PATH)
@@ -96,14 +97,14 @@
 
 
 def get_netanim(ns3_dir):
-    print """
+    print("""
     #
     # Get NetAnim
     #
-    """
+    """)
 
     if sys.platform in ['cygwin']:
-	print "Architecture (%s) does not support NetAnim... skipping" % (sys.platform)
+        print("Architecture (%s) does not support NetAnim... skipping" % (sys.platform))
         raise RuntimeError
 
     # (peek into the ns-3 wscript and extract the required netanim version)
@@ -111,7 +112,7 @@
         # For the recent versions
         netanim_wscript = open(os.path.join(ns3_dir, "src", "netanim", "wscript"), "rt")
     except:
-        print "Unable to detect NetAnim required version.Skipping download"
+        print("Unable to detect NetAnim required version.Skipping download")
         pass
         return
 
@@ -123,25 +124,25 @@
     netanim_wscript.close()
     if required_netanim_version is None:
         fatal("Unable to detect NetAnim required version")
-    print "Required NetAnim version: ", required_netanim_version
+    print("Required NetAnim version: ", required_netanim_version)
 
 
     def netanim_clone():
-        print "Retrieving NetAnim from " + constants.NETANIM_REPO
+        print("Retrieving NetAnim from " + constants.NETANIM_REPO)
         run_command(['hg', 'clone', constants.NETANIM_REPO, constants.LOCAL_NETANIM_PATH])
 
     def netanim_update():
-        print "Pulling NetAnim updates from " + constants.NETANIM_REPO
+        print("Pulling NetAnim updates from " + constants.NETANIM_REPO)
         run_command(['hg', '--cwd', constants.LOCAL_NETANIM_PATH, 'pull', '-u', constants.NETANIM_REPO])
 
     def netanim_download():
         local_file = required_netanim_version + ".tar.bz2"
         remote_file = constants.NETANIM_RELEASE_URL + "/" + local_file
-        print "Retrieving NetAnim from " + remote_file
+        print("Retrieving NetAnim from " + remote_file)
         urllib.urlretrieve(remote_file, local_file)
-        print "Uncompressing " + local_file
+        print("Uncompressing " + local_file)
         run_command(["tar", "-xjf", local_file])
-        print "Rename %s as %s" % (required_netanim_version, constants.LOCAL_NETANIM_PATH)
+        print("Rename %s as %s" % (required_netanim_version, constants.LOCAL_NETANIM_PATH))
         os.rename(required_netanim_version, constants.LOCAL_NETANIM_PATH)
 
     if not os.path.exists(os.path.join(ns3_dir, '.hg')):
@@ -155,21 +156,21 @@
 
 
 def get_bake(ns3_dir):
-    print """
+    print("""
     #
     # Get bake
     #
-    """
+    """)
 
     def bake_clone():
-        print "Retrieving bake from " + constants.BAKE_REPO
+        print("Retrieving bake from " + constants.BAKE_REPO)
         run_command(['hg', 'clone', constants.BAKE_REPO])
     def bake_download():
         # Bake does not provide download tarballs; clone instead
         bake_clone()
 
     def bake_update():
-        print "Pulling bake updates from " + constants.BAKE_REPO
+        print("Pulling bake updates from " + constants.BAKE_REPO)
         run_command(['hg', '--cwd', 'bake', 'pull', '-u', constants.BAKE_REPO])
 
     if not os.path.exists(os.path.join(ns3_dir, '.hg')):
@@ -204,7 +205,7 @@
     try:
         pybindgen_dir, pybindgen_version = get_pybindgen(ns3_dir)
     except (CommandError, OSError, RuntimeError) as ex:
-        print " *** Did not fetch pybindgen ({}); python bindings will not be available.".format(ex)
+        print(" *** Did not fetch pybindgen ({}); python bindings will not be available.".format(ex))
     else:
         pybindgen_config = config.documentElement.appendChild(config.createElement("pybindgen"))
         pybindgen_config.setAttribute("dir", pybindgen_dir)
@@ -212,22 +213,22 @@
 
     # -- download NetAnim --
     try:
-	netanim_dir, netanim_version = get_netanim(ns3_dir)
+        netanim_dir, netanim_version = get_netanim(ns3_dir)
     except (CommandError, IOError, RuntimeError):
-	print " *** Did not fetch NetAnim offline animator. Please visit http://www.nsnam.org/wiki/index.php/NetAnim ."
+        print(" *** Did not fetch NetAnim offline animator. Please visit http://www.nsnam.org/wiki/index.php/NetAnim .")
     else:
-	netanim_config = config.documentElement.appendChild(config.createElement("netanim"))
-	netanim_config.setAttribute("dir", netanim_dir)
+        netanim_config = config.documentElement.appendChild(config.createElement("netanim"))
+        netanim_config.setAttribute("dir", netanim_dir)
         netanim_config.setAttribute("version", netanim_version)
 
     # -- download bake --
     try:
-	get_bake(ns3_dir)
+        get_bake(ns3_dir)
     except (CommandError, IOError, RuntimeError):
-	print " *** Did not fetch bake build tool."
+        print(" *** Did not fetch bake build tool.")
     else:
-	bake_config = config.documentElement.appendChild(config.createElement("bake"))
-	bake_config.setAttribute("dir", "bake")
+        bake_config = config.documentElement.appendChild(config.createElement("bake"))
+        bake_config.setAttribute("dir", "bake")
         bake_config.setAttribute("version", "bake")
 
     # write the config to a file
--- a/util.py	Sun Jul 26 14:02:12 2015 +0100
+++ b/util.py	Thu Sep 03 18:28:56 2015 -0700
@@ -1,8 +1,9 @@
+from __future__ import print_function
 import sys
 import subprocess
 
 def fatal(msg):
-    print >> sys.stderr, msg
+    print(msg, file=sys.stderr)
     sys.exit(2)
 
 class CommandError(Exception):
@@ -16,7 +17,7 @@
     else:
         argv = None
     if argv is not None:
-        print " => ", ' '.join(argv)
+        print(" => ", ' '.join(argv))
 
     cmd = subprocess.Popen(*args, **kwargs)
     retval = cmd.wait()