so = os.popen("tee \"%s\"" % logfile, "w")
         else:
             so = file(logfile, 'w')
-    except OSError, e:
+    except OSError as e:
         bb.msg.error(bb.msg.domain.Build, "opening log file: %s" % e)
         pass
 
         event.fire(TaskStarted(task, localdata), localdata)
         exec_func(task, localdata)
         event.fire(TaskSucceeded(task, localdata), localdata)
-    except FuncFailed, message:
+    except FuncFailed as message:
         # Try to extract the optional logfile
         try:
             (msg, logfile) = message
 
             return
 
         self.has_cache = True
-        self.cachefile = os.path.join(self.cachedir,"bb_cache.dat")
+        self.cachefile = os.path.join(self.cachedir, "bb_cache.dat")
 
         bb.msg.debug(1, bb.msg.domain.Cache, "Using cache in '%s'" % self.cachedir)
         try:
                 p = pickle.Unpickler(file(self.cachefile, "rb"))
                 self.depends_cache, version_data = p.load()
                 if version_data['CACHE_VER'] != __cache_version__:
-                    raise ValueError, 'Cache Version Mismatch'
+                    raise ValueError('Cache Version Mismatch')
                 if version_data['BITBAKE_VER'] != bb.__version__:
-                    raise ValueError, 'Bitbake Version Mismatch'
+                    raise ValueError('Bitbake Version Mismatch')
             except EOFError:
                 bb.msg.note(1, bb.msg.domain.Cache, "Truncated cache found, rebuilding...")
                 self.depends_cache = {}
         self.getVar('__BB_DONT_CACHE', file_name, True)
         self.getVar('__VARIANTS', file_name, True)
 
-    def load_bbfile( self, bbfile , config):
+    def load_bbfile( self, bbfile, config):
         """
         Load and parse one .bb build file
         Return the data and whether parsing resulted in the file being skipped
 
-"""\r
-Python Deamonizing helper\r
-\r
-Configurable daemon behaviors:\r
-\r
-    1.) The current working directory set to the "/" directory.\r
-    2.) The current file creation mode mask set to 0.\r
-    3.) Close all open files (1024). \r
-    4.) Redirect standard I/O streams to "/dev/null".\r
-\r
-A failed call to fork() now raises an exception.\r
-\r
-References:\r
-    1) Advanced Programming in the Unix Environment: W. Richard Stevens\r
-    2) Unix Programming Frequently Asked Questions:\r
-            http://www.erlenstar.demon.co.uk/unix/faq_toc.html\r
-\r
-Modified to allow a function to be daemonized and return for \r
-bitbake use by Richard Purdie\r
-"""\r
-\r
-__author__ = "Chad J. Schroeder"\r
-__copyright__ = "Copyright (C) 2005 Chad J. Schroeder"\r
-__version__ = "0.2"\r
-\r
-# Standard Python modules.\r
-import os                    # Miscellaneous OS interfaces.\r
-import sys                  # System-specific parameters and functions.\r
-\r
-# Default daemon parameters.\r
-# File mode creation mask of the daemon.\r
-# For BitBake's children, we do want to inherit the parent umask.\r
-UMASK = None\r
-\r
-# Default maximum for the number of available file descriptors.\r
-MAXFD = 1024\r
-\r
-# The standard I/O file descriptors are redirected to /dev/null by default.\r
-if (hasattr(os, "devnull")):\r
-    REDIRECT_TO = os.devnull\r
-else:\r
-    REDIRECT_TO = "/dev/null"\r
-\r
-def createDaemon(function, logfile):\r
-    """\r
-    Detach a process from the controlling terminal and run it in the\r
-    background as a daemon, returning control to the caller.\r
-    """\r
-\r
-    try:\r
-        # Fork a child process so the parent can exit.  This returns control to\r
-        # the command-line or shell.  It also guarantees that the child will not\r
-        # be a process group leader, since the child receives a new process ID\r
-        # and inherits the parent's process group ID.  This step is required\r
-        # to insure that the next call to os.setsid is successful.\r
-        pid = os.fork()\r
-    except OSError, e:\r
-        raise Exception, "%s [%d]" % (e.strerror, e.errno)\r
-\r
-    if (pid == 0):      # The first child.\r
-        # To become the session leader of this new session and the process group\r
-        # leader of the new process group, we call os.setsid().  The process is\r
-        # also guaranteed not to have a controlling terminal.\r
-        os.setsid()\r
-\r
-        # Is ignoring SIGHUP necessary?\r
-        #\r
-        # It's often suggested that the SIGHUP signal should be ignored before\r
-        # the second fork to avoid premature termination of the process.  The\r
-        # reason is that when the first child terminates, all processes, e.g.\r
-        # the second child, in the orphaned group will be sent a SIGHUP.\r
-        #\r
-        # "However, as part of the session management system, there are exactly\r
-        # two cases where SIGHUP is sent on the death of a process:\r
-        #\r
-        #    1) When the process that dies is the session leader of a session that\r
-        #        is attached to a terminal device, SIGHUP is sent to all processes\r
-        #        in the foreground process group of that terminal device.\r
-        #    2) When the death of a process causes a process group to become\r
-        #        orphaned, and one or more processes in the orphaned group are\r
-        #        stopped, then SIGHUP and SIGCONT are sent to all members of the\r
-        #        orphaned group." [2]\r
-        #\r
-        # The first case can be ignored since the child is guaranteed not to have\r
-        # a controlling terminal.  The second case isn't so easy to dismiss.\r
-        # The process group is orphaned when the first child terminates and\r
-        # POSIX.1 requires that every STOPPED process in an orphaned process\r
-        # group be sent a SIGHUP signal followed by a SIGCONT signal.  Since the\r
-        # second child is not STOPPED though, we can safely forego ignoring the\r
-        # SIGHUP signal.  In any case, there are no ill-effects if it is ignored.\r
-        #\r
-        # import signal              # Set handlers for asynchronous events.\r
-        # signal.signal(signal.SIGHUP, signal.SIG_IGN)\r
-\r
-        try:\r
-            # Fork a second child and exit immediately to prevent zombies.  This\r
-            # causes the second child process to be orphaned, making the init\r
-            # process responsible for its cleanup.  And, since the first child is\r
-            # a session leader without a controlling terminal, it's possible for\r
-            # it to acquire one by opening a terminal in the future (System V-\r
-            # based systems).  This second fork guarantees that the child is no\r
-            # longer a session leader, preventing the daemon from ever acquiring\r
-            # a controlling terminal.\r
-            pid = os.fork()     # Fork a second child.\r
-        except OSError, e:\r
-            raise Exception, "%s [%d]" % (e.strerror, e.errno)\r
-\r
-        if (pid == 0):  # The second child.\r
-            # We probably don't want the file mode creation mask inherited from\r
-            # the parent, so we give the child complete control over permissions.\r
-            if UMASK is not None:\r
-                os.umask(UMASK)\r
-        else:\r
-            # Parent (the first child) of the second child.\r
-            os._exit(0)\r
-    else:\r
-        # exit() or _exit()?\r
-        # _exit is like exit(), but it doesn't call any functions registered\r
-        # with atexit (and on_exit) or any registered signal handlers.  It also\r
-        # closes any open file descriptors.  Using exit() may cause all stdio\r
-        # streams to be flushed twice and any temporary files may be unexpectedly\r
-        # removed.  It's therefore recommended that child branches of a fork()\r
-        # and the parent branch(es) of a daemon use _exit().\r
-        return\r
-\r
-    # Close all open file descriptors.  This prevents the child from keeping\r
-    # open any file descriptors inherited from the parent.  There is a variety\r
-    # of methods to accomplish this task.  Three are listed below.\r
-    #\r
-    # Try the system configuration variable, SC_OPEN_MAX, to obtain the maximum\r
-    # number of open file descriptors to close.  If it doesn't exists, use\r
-    # the default value (configurable).\r
-    #\r
-    # try:\r
-    #     maxfd = os.sysconf("SC_OPEN_MAX")\r
-    # except (AttributeError, ValueError):\r
-    #     maxfd = MAXFD\r
-    #\r
-    # OR\r
-    #\r
-    # if (os.sysconf_names.has_key("SC_OPEN_MAX")):\r
-    #     maxfd = os.sysconf("SC_OPEN_MAX")\r
-    # else:\r
-    #     maxfd = MAXFD\r
-    #\r
-    # OR\r
-    #\r
-    # Use the getrlimit method to retrieve the maximum file descriptor number\r
-    # that can be opened by this process.  If there is not limit on the\r
-    # resource, use the default value.\r
-    #\r
-    import resource             # Resource usage information.\r
-    maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]\r
-    if (maxfd == resource.RLIM_INFINITY):\r
-        maxfd = MAXFD\r
-  \r
-    # Iterate through and close all file descriptors.\r
-#    for fd in range(0, maxfd):\r
-#        try:\r
-#            os.close(fd)\r
-#        except OSError:        # ERROR, fd wasn't open to begin with (ignored)\r
-#            pass\r
-\r
-    # Redirect the standard I/O file descriptors to the specified file.  Since\r
-    # the daemon has no controlling terminal, most daemons redirect stdin,\r
-    # stdout, and stderr to /dev/null.  This is done to prevent side-effects\r
-    # from reads and writes to the standard I/O file descriptors.\r
-\r
-    # This call to open is guaranteed to return the lowest file descriptor,\r
-    # which will be 0 (stdin), since it was closed above.\r
-#    os.open(REDIRECT_TO, os.O_RDWR)    # standard input (0)\r
-\r
-    # Duplicate standard input to standard output and standard error.\r
-#    os.dup2(0, 1)                      # standard output (1)\r
-#    os.dup2(0, 2)                      # standard error (2)\r
-\r
-\r
-    si = file('/dev/null', 'r')\r
-    so = file(logfile, 'w')\r
-    se = so\r
-\r
-\r
-    # Replace those fds with our own\r
-    os.dup2(si.fileno(), sys.stdin.fileno())\r
-    os.dup2(so.fileno(), sys.stdout.fileno())\r
-    os.dup2(se.fileno(), sys.stderr.fileno())\r
-\r
-    function()\r
-\r
-    os._exit(0)\r
+"""
+Python Deamonizing helper
+
+Configurable daemon behaviors:
+
+    1.) The current working directory set to the "/" directory.
+    2.) The current file creation mode mask set to 0.
+    3.) Close all open files (1024). 
+    4.) Redirect standard I/O streams to "/dev/null".
+
+A failed call to fork() now raises an exception.
+
+References:
+    1) Advanced Programming in the Unix Environment: W. Richard Stevens
+    2) Unix Programming Frequently Asked Questions:
+            http://www.erlenstar.demon.co.uk/unix/faq_toc.html
+
+Modified to allow a function to be daemonized and return for 
+bitbake use by Richard Purdie
+"""
+
+__author__ = "Chad J. Schroeder"
+__copyright__ = "Copyright (C) 2005 Chad J. Schroeder"
+__version__ = "0.2"
+
+# Standard Python modules.
+import os                    # Miscellaneous OS interfaces.
+import sys                  # System-specific parameters and functions.
+
+# Default daemon parameters.
+# File mode creation mask of the daemon.
+# For BitBake's children, we do want to inherit the parent umask.
+UMASK = None
+
+# Default maximum for the number of available file descriptors.
+MAXFD = 1024
+
+# The standard I/O file descriptors are redirected to /dev/null by default.
+if (hasattr(os, "devnull")):
+    REDIRECT_TO = os.devnull
+else:
+    REDIRECT_TO = "/dev/null"
+
+def createDaemon(function, logfile):
+    """
+    Detach a process from the controlling terminal and run it in the
+    background as a daemon, returning control to the caller.
+    """
+
+    try:
+        # Fork a child process so the parent can exit.  This returns control to
+        # the command-line or shell.  It also guarantees that the child will not
+        # be a process group leader, since the child receives a new process ID
+        # and inherits the parent's process group ID.  This step is required
+        # to insure that the next call to os.setsid is successful.
+        pid = os.fork()
+    except OSError as e:
+        raise Exception("%s [%d]" % (e.strerror, e.errno))
+
+    if (pid == 0):      # The first child.
+        # To become the session leader of this new session and the process group
+        # leader of the new process group, we call os.setsid().  The process is
+        # also guaranteed not to have a controlling terminal.
+        os.setsid()
+
+        # Is ignoring SIGHUP necessary?
+        #
+        # It's often suggested that the SIGHUP signal should be ignored before
+        # the second fork to avoid premature termination of the process.  The
+        # reason is that when the first child terminates, all processes, e.g.
+        # the second child, in the orphaned group will be sent a SIGHUP.
+        #
+        # "However, as part of the session management system, there are exactly
+        # two cases where SIGHUP is sent on the death of a process:
+        #
+        #    1) When the process that dies is the session leader of a session that
+        #        is attached to a terminal device, SIGHUP is sent to all processes
+        #        in the foreground process group of that terminal device.
+        #    2) When the death of a process causes a process group to become
+        #        orphaned, and one or more processes in the orphaned group are
+        #        stopped, then SIGHUP and SIGCONT are sent to all members of the
+        #        orphaned group." [2]
+        #
+        # The first case can be ignored since the child is guaranteed not to have
+        # a controlling terminal.  The second case isn't so easy to dismiss.
+        # The process group is orphaned when the first child terminates and
+        # POSIX.1 requires that every STOPPED process in an orphaned process
+        # group be sent a SIGHUP signal followed by a SIGCONT signal.  Since the
+        # second child is not STOPPED though, we can safely forego ignoring the
+        # SIGHUP signal.  In any case, there are no ill-effects if it is ignored.
+        #
+        # import signal              # Set handlers for asynchronous events.
+        # signal.signal(signal.SIGHUP, signal.SIG_IGN)
+
+        try:
+            # Fork a second child and exit immediately to prevent zombies.  This
+            # causes the second child process to be orphaned, making the init
+            # process responsible for its cleanup.  And, since the first child is
+            # a session leader without a controlling terminal, it's possible for
+            # it to acquire one by opening a terminal in the future (System V-
+            # based systems).  This second fork guarantees that the child is no
+            # longer a session leader, preventing the daemon from ever acquiring
+            # a controlling terminal.
+            pid = os.fork()     # Fork a second child.
+        except OSError as e:
+            raise Exception("%s [%d]" % (e.strerror, e.errno))
+
+        if (pid == 0):  # The second child.
+            # We probably don't want the file mode creation mask inherited from
+            # the parent, so we give the child complete control over permissions.
+            if UMASK is not None:
+                os.umask(UMASK)
+        else:
+            # Parent (the first child) of the second child.
+            os._exit(0)
+    else:
+        # exit() or _exit()?
+        # _exit is like exit(), but it doesn't call any functions registered
+        # with atexit (and on_exit) or any registered signal handlers.  It also
+        # closes any open file descriptors.  Using exit() may cause all stdio
+        # streams to be flushed twice and any temporary files may be unexpectedly
+        # removed.  It's therefore recommended that child branches of a fork()
+        # and the parent branch(es) of a daemon use _exit().
+        return
+
+    # Close all open file descriptors.  This prevents the child from keeping
+    # open any file descriptors inherited from the parent.  There is a variety
+    # of methods to accomplish this task.  Three are listed below.
+    #
+    # Try the system configuration variable, SC_OPEN_MAX, to obtain the maximum
+    # number of open file descriptors to close.  If it doesn't exists, use
+    # the default value (configurable).
+    #
+    # try:
+    #     maxfd = os.sysconf("SC_OPEN_MAX")
+    # except (AttributeError, ValueError):
+    #     maxfd = MAXFD
+    #
+    # OR
+    #
+    # if (os.sysconf_names.has_key("SC_OPEN_MAX")):
+    #     maxfd = os.sysconf("SC_OPEN_MAX")
+    # else:
+    #     maxfd = MAXFD
+    #
+    # OR
+    #
+    # Use the getrlimit method to retrieve the maximum file descriptor number
+    # that can be opened by this process.  If there is not limit on the
+    # resource, use the default value.
+    #
+    import resource             # Resource usage information.
+    maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
+    if (maxfd == resource.RLIM_INFINITY):
+        maxfd = MAXFD
+  
+    # Iterate through and close all file descriptors.
+#    for fd in range(0, maxfd):
+#        try:
+#            os.close(fd)
+#        except OSError:        # ERROR, fd wasn't open to begin with (ignored)
+#            pass
+
+    # Redirect the standard I/O file descriptors to the specified file.  Since
+    # the daemon has no controlling terminal, most daemons redirect stdin,
+    # stdout, and stderr to /dev/null.  This is done to prevent side-effects
+    # from reads and writes to the standard I/O file descriptors.
+
+    # This call to open is guaranteed to return the lowest file descriptor,
+    # which will be 0 (stdin), since it was closed above.
+#    os.open(REDIRECT_TO, os.O_RDWR)    # standard input (0)
+
+    # Duplicate standard input to standard output and standard error.
+#    os.dup2(0, 1)                      # standard output (1)
+#    os.dup2(0, 2)                      # standard error (2)
+
+
+    si = file('/dev/null', 'r')
+    so = file(logfile, 'w')
+    se = so
+
+
+    # Replace those fds with our own
+    os.dup2(si.fileno(), sys.stdin.fileno())
+    os.dup2(so.fileno(), sys.stdout.fileno())
+    os.dup2(se.fileno(), sys.stderr.fileno())
+
+    function()
+
+    os._exit(0)
 
     if all:
         o.write('# %s=%s\n' % (var, oval))
 
-    if type(val) is not types.StringType:
+    if not isinstance(val, types.StringType):
         return 0
 
     if (var.find("-") != -1 or var.find(".") != -1 or var.find('{') != -1 or var.find('}') != -1 or var.find('+') != -1) and not all:
 
             code = match.group()[3:-1]
             codeobj = compile(code.strip(), varname or "<expansion>", "eval")
             s = utils.better_eval(codeobj, {"d": self})
-            if type(s) == types.IntType: s = str(s)
+            if isinstance(s, types.IntType): s = str(s)
             return s
 
-        if type(s) is not types.StringType: # sanity check
+        if not isinstance(s, types.StringType): # sanity check
             return s
 
         if varname and varname in self.expand_cache:
                 s = __expand_var_regexp__.sub(var_sub, s)
                 s = __expand_python_regexp__.sub(python_sub, s)
                 if s == olds: break
-                if type(s) is not types.StringType: # sanity check
+                if not isinstance(s, types.StringType): # sanity check
                     bb.msg.error(bb.msg.domain.Data, 'expansion of %s returned non-string %s' % (olds, s))
             except KeyboardInterrupt:
                 raise
             l    = len(o)+1
 
             # see if one should even try
-            if not self._seen_overrides.has_key(o):
+            if o not in self._seen_overrides:
                 continue
 
             vars = self._seen_overrides[o]
                     bb.msg.note(1, bb.msg.domain.Data, "Untracked delVar")
 
         # now on to the appends and prepends
-        if self._special_values.has_key("_append"):
+        if "_append" in self._special_values:
             appends = self._special_values['_append'] or []
             for append in appends:
                 for (a, o) in self.getVarFlag(append, '_append') or []:
                     self.setVar(append, sval)
 
 
-        if self._special_values.has_key("_prepend"):
+        if "_prepend" in self._special_values:
             prepends = self._special_values['_prepend'] or []
 
             for prepend in prepends:
         # more cookies for the cookie monster
         if '_' in var:
             override = var[var.rfind('_')+1:]
-            if not self._seen_overrides.has_key(override):
+            if override not in self._seen_overrides:
                 self._seen_overrides[override] = set()
             self._seen_overrides[override].add( var )
 
             dest.extend(src)
             self.setVarFlag(newkey, i, dest)
 
-            if self._special_values.has_key(i) and key in self._special_values[i]:
+            if i in self._special_values and key in self._special_values[i]:
                 self._special_values[i].remove(key)
                 self._special_values[i].add(newkey)
 
 
         bb.msg.debug(2, bb.msg.domain.Fetcher, "Fetch: checking for module directory")
         pkg = data.expand('${PN}', d)
         pkgdir = os.path.join(data.expand('${CVSDIR}', localdata), pkg)
-        moddir = os.path.join(pkgdir,localdir)
-        if os.access(os.path.join(moddir,'CVS'), os.R_OK):
+        moddir = os.path.join(pkgdir, localdir)
+        if os.access(os.path.join(moddir, 'CVS'), os.R_OK):
             bb.msg.note(1, bb.msg.domain.Fetcher, "Update " + loc)
             # update sources there
             os.chdir(moddir)
 
     def supports(self, url, ud, d):
         return ud.type in ['p4']
 
-    def doparse(url,d):
+    def doparse(url, d):
         parm = {}
         path = url.split("://")[1]
         delim = path.find("@");
         if delim != -1:
-            (user,pswd,host,port) = path.split('@')[0].split(":")
+            (user, pswd, host, port) = path.split('@')[0].split(":")
             path = path.split('@')[1]
         else:
-            (host,port) = data.getVar('P4PORT', d).split(':')
+            (host, port) = data.getVar('P4PORT', d).split(':')
             user = ""
             pswd = ""
 
             plist = path.split(';')
             for item in plist:
                 if item.count('='):
-                    (key,value) = item.split('=')
+                    (key, value) = item.split('=')
                     keys.append(key)
                     values.append(value)
 
-            parm = dict(zip(keys,values))
+            parm = dict(zip(keys, values))
         path = "//" + path.split(';')[0]
         host += ":%s" % (port)
         parm["cset"] = Perforce.getcset(d, path, host, user, pswd, parm)
 
-        return host,path,user,pswd,parm
+        return host, path, user, pswd, parm
     doparse = staticmethod(doparse)
 
-    def getcset(d, depot,host,user,pswd,parm):
+    def getcset(d, depot, host, user, pswd, parm):
         p4opt = ""
         if "cset" in parm:
             return parm["cset"];
 
     def localpath(self, url, ud, d):
 
-        (host,path,user,pswd,parm) = Perforce.doparse(url,d)
+        (host, path, user, pswd, parm) = Perforce.doparse(url, d)
 
         # If a label is specified, we use that as our filename
 
 
         cset = Perforce.getcset(d, path, host, user, pswd, parm)
 
-        ud.localfile = data.expand('%s+%s+%s.tar.gz' % (host,base.replace('/', '.'), cset), d)
+        ud.localfile = data.expand('%s+%s+%s.tar.gz' % (host, base.replace('/', '.'), cset), d)
 
         return os.path.join(data.getVar("DL_DIR", d, 1), ud.localfile)
 
         Fetch urls
         """
 
-        (host,depot,user,pswd,parm) = Perforce.doparse(loc, d)
+        (host, depot, user, pswd, parm) = Perforce.doparse(loc, d)
 
         if depot.find('/...') != -1:
             path = depot[:depot.find('/...')]
             raise FetchError(module)
 
         if "label" in parm:
-            depot = "%s@%s" % (depot,parm["label"])
+            depot = "%s@%s" % (depot, parm["label"])
         else:
             cset = Perforce.getcset(d, depot, host, user, pswd, parm)
-            depot = "%s@%s" % (depot,cset)
+            depot = "%s@%s" % (depot, cset)
 
         os.chdir(tmpfile)
         bb.msg.note(1, bb.msg.domain.Fetcher, "Fetch " + loc)
             dest = list[0][len(path)+1:]
             where = dest.find("#")
 
-            os.system("%s%s print -o %s/%s %s" % (p4cmd, p4opt, module,dest[:where],list[0]))
+            os.system("%s%s print -o %s/%s %s" % (p4cmd, p4opt, module, dest[:where], list[0]))
             count = count + 1
 
         if count == 0:
 
         """
         Check to see if a given url can be fetched with wget.
         """
-        return ud.type in ['http','https','ftp']
+        return ud.type in ['http', 'https', 'ftp']
 
     def localpath(self, url, ud, d):
 
 
 
 __mtime_cache = {}
 def cached_mtime(f):
-    if not __mtime_cache.has_key(f):
+    if f not in __mtime_cache:
         __mtime_cache[f] = os.stat(f)[8]
     return __mtime_cache[f]
 
 def cached_mtime_noerror(f):
-    if not __mtime_cache.has_key(f):
+    if f not in __mtime_cache:
         try:
             __mtime_cache[f] = os.stat(f)[8]
         except OSError:
 
     all_handlers = {}
     for var in bb.data.getVar('__BBHANDLERS', d) or []:
         # try to add the handler
-        handler = bb.data.getVar(var,d)
+        handler = bb.data.getVar(var, d)
         bb.event.register(var, handler)
 
     tasklist = bb.data.getVar('__BBTASKS', d) or []
 
         statements = ast.StatementGroup()
 
         lineno = 0
-        while 1:
+        while True:
             lineno = lineno + 1
             s = file.readline()
             if not s: break
         bb.msg.debug(2, bb.msg.domain.Parsing, "BB " + fn + ": handle(data, include)")
 
     (root, ext) = os.path.splitext(os.path.basename(fn))
-    base_name = "%s%s" % (root,ext)
+    base_name = "%s%s" % (root, ext)
     init(d)
 
     if ext == ".bbclass":
     return d
 
 def feeder(lineno, s, fn, root, statements):
-    global __func_start_regexp__, __inherit_regexp__, __export_func_regexp__, __addtask_regexp__, __addhandler_regexp__, __def_regexp__, __python_func_regexp__, __inpython__,__infunc__, __body__, classes, bb, __residue__
+    global __func_start_regexp__, __inherit_regexp__, __export_func_regexp__, __addtask_regexp__, __addhandler_regexp__, __def_regexp__, __python_func_regexp__, __inpython__, __infunc__, __body__, classes, bb, __residue__
     if __infunc__:
         if s == '}':
             __body__.append('')
 
 
     statements = ast.StatementGroup()
     lineno = 0
-    while 1:
+    while True:
         lineno = lineno + 1
         s = f.readline()
         if not s: break
 
         except OSError:
             bb.utils.mkdirhier(self.cachedir)
 
-        self.cachefile = os.path.join(self.cachedir,"bb_persist_data.sqlite3")
+        self.cachefile = os.path.join(self.cachedir, "bb_persist_data.sqlite3")
         bb.msg.debug(1, bb.msg.domain.PersistData, "Using '%s' as the persistent data cache" % self.cachefile)
 
         self.connection = sqlite3.connect(self.cachefile, timeout=5, isolation_level=None)
             try:
                 self.connection.execute(*query)
                 return
-            except sqlite3.OperationalError, e:
+            except sqlite3.OperationalError as e:
                 if 'database is locked' in str(e):
                     continue
                 raise
 
 
         self.rq = runqueue
 
-        sortweight = deepcopy(self.rq.runq_weight)
-        sortweight.sort()
+        sortweight = sorted(deepcopy(self.rq.runq_weight))
         copyweight = deepcopy(self.rq.runq_weight)
         self.prio_map = []
 
             weight[listid] = 1
             task_done[listid] = True
 
-        while 1:
+        while True:
             next_points = []
             for listid in endpoints:
                 for revdep in self.runq_depends[listid]:
             for dep in revdeps:
                 if dep in self.runq_depends[listid]:
                     #self.dump_data(taskData)
-                    bb.msg.fatal(bb.msg.domain.RunQueue, "Task %s (%s) has circular dependency on %s (%s)" % (taskData.fn_index[self.runq_fnid[dep]], self.runq_task[dep] , taskData.fn_index[self.runq_fnid[listid]], self.runq_task[listid]))
+                    bb.msg.fatal(bb.msg.domain.RunQueue, "Task %s (%s) has circular dependency on %s (%s)" % (taskData.fn_index[self.runq_fnid[dep]], self.runq_task[dep], taskData.fn_index[self.runq_fnid[listid]], self.runq_task[listid]))
 
         bb.msg.note(2, bb.msg.domain.RunQueue, "Compute totals (have %s endpoint(s))" % len(endpoints))
 
                             bb.msg.debug(2, bb.msg.domain.RunQueue, "Stampfile %s < %s" % (stampfile, stampfile2))
                             iscurrent = False
                     except:
-                        bb.msg.debug(2, bb.msg.domain.RunQueue, "Exception reading %s for %s" % (stampfile2 , stampfile))
+                        bb.msg.debug(2, bb.msg.domain.RunQueue, "Exception reading %s for %s" % (stampfile2, stampfile))
                         iscurrent = False
 
         return iscurrent
                 try:
                     pipein, pipeout = os.pipe()
                     pid = os.fork() 
-                except OSError, e: 
+                except OSError as e: 
                     bb.msg.fatal(bb.msg.domain.RunQueue, "fork failed: %d (%s)" % (e.errno, e.strerror))
                 if pid == 0:
                     os.close(pipein)
 
 
     def register_idle_function(self, function, data):
         """Register a function to be called while the server is idle"""
-        assert callable(function)
+        assert hasattr(function, '__call__')
         self._idlefuns[function] = data
 
     def idle_commands(self, delay):
 
 
     def register_idle_function(self, function, data):
         """Register a function to be called while the server is idle"""
-        assert callable(function)
+        assert hasattr(function, '__call__')
         self._idlefuns[function] = data
 
     def serve_forever(self):
 
 
     for name in strings:
         if (name==target or
-                re.search(name,target)!=None):
+                re.search(name, target)!=None):
             return True
     return False
 
         Resolve all unresolved build and runtime targets
         """
         bb.msg.note(1, bb.msg.domain.TaskData, "Resolving any missing task queue dependencies")
-        while 1:
+        while True:
             added = 0
             for target in self.get_unresolved_build_targets(dataCache):
                 try:
 
         # format build-<year><month><day>-<ordinal> we can easily
         # pull it out.
         # TODO: Better to stat a file?
-        (_ , date, revision) = identifier.split ("-")
+        (_, date, revision) = identifier.split ("-")
         print(date)
 
         year = int (date[0:4])
                 build_directory])
             server.runCommand(["buildTargets", [conf.image], "rootfs"])
 
-        except Exception, e:
+        except Exception as e:
             print(e)
 
 class BuildManagerTreeView (gtk.TreeView):
 
         # for the message.
         if hasattr(event, 'pid'):
             pid = event.pid
-            if self.pids_to_task.has_key(pid):
+            if pid in self.pids_to_task:
                 (package, task) = self.pids_to_task[pid]
                 parent = self.tasks_to_iter[(package, task)]
 
             (package, task) = (event._package, event._task)
 
             # Save out this PID.
-            self.pids_to_task[pid] = (package,task)
+            self.pids_to_task[pid] = (package, task)
 
             # Check if we already have this package in our model. If so then
             # that can be the parent for the task. Otherwise we create a new
             # top level for the package.
-            if (self.tasks_to_iter.has_key ((package, None))):
+            if ((package, None) in self.tasks_to_iter):
                 parent = self.tasks_to_iter[(package, None)]
             else:
                 parent = self.model.append (None, (None,
 
         if ret != True:
             print("Couldn't run command! %s" % ret)
             return
-    except xmlrpclib.Fault, x:
+    except xmlrpclib.Fault as x:
         print("XMLRPC Fault getting commandline:\n %s" % x)
         return
 
 
         if ret != True:
             print("Couldn't get default commandline! %s" % ret)
             return 1
-    except xmlrpclib.Fault, x:
+    except xmlrpclib.Fault as x:
         print("XMLRPC Fault getting commandline:\n %s" % x)
         return 1
 
 
         if ret != True:
             print("Couldn't get default commandline! %s" % ret)
             return 1
-    except xmlrpclib.Fault, x:
+    except xmlrpclib.Fault as x:
         print("XMLRPC Fault getting commandline:\n %s" % x)
         return 1
 
 
             if ret != True:
                 print("Couldn't get default commandlind! %s" % ret)
                 return
-        except xmlrpclib.Fault, x:
+        except xmlrpclib.Fault as x:
             print("XMLRPC Fault getting commandline:\n %s" % x)
             return
 
 
                 gobject.idle_add (MetaDataLoader.emit_success_signal,
                     self.loader)
 
-            except MetaDataLoader.LoaderThread.LoaderImportException, e:
+            except MetaDataLoader.LoaderThread.LoaderImportException as e:
                 gobject.idle_add (MetaDataLoader.emit_error_signal, self.loader,
                     "Repository metadata corrupt")
-            except Exception, e:
+            except Exception as e:
                 gobject.idle_add (MetaDataLoader.emit_error_signal, self.loader,
                     "Unable to download repository metadata")
                 print(e)
         # Build
         button = gtk.Button ("_Build", None, True)
         image = gtk.Image ()
-        image.set_from_stock (gtk.STOCK_EXECUTE,gtk.ICON_SIZE_BUTTON)
+        image.set_from_stock (gtk.STOCK_EXECUTE, gtk.ICON_SIZE_BUTTON)
         button.set_image (image)
         self.add_action_widget (button, BuildSetupDialog.RESPONSE_BUILD)
         button.show_all ()
 
                 return (sock, addr)
             except socket.timeout:
                 pass
-        return (None,None)
+        return (None, None)
 
     def close_request(self, request):
         if request is None:
 
         if ca == None and cb == None:
             return 0
 
-        if type(ca) is types.StringType:
+        if isinstance(ca, types.StringType):
             sa = ca in separators
-        if type(cb) is types.StringType:
+        if isinstance(cb, types.StringType):
             sb = cb in separators
         if sa and not sb:
             return -1
     """
     try:
         return compile(text, file, mode)
-    except Exception, e:
+    except Exception as e:
         # split the text into lines again
         body = text.split('\n')
         bb.msg.error(bb.msg.domain.Util, "Error in compiling python function in: ", realfile)
                     return lf
             # File no longer exists or changed, retry
             lf.close
-        except Exception, e:
+        except Exception as e:
             continue
 
 def unlockfile(lf):
     try:
         os.makedirs(dir)
         bb.msg.debug(2, bb.msg.domain.Util, "created " + dir)
-    except OSError, e:
+    except OSError as e:
         if e.errno != errno.EEXIST:
             raise e
 
     try:
         if not sstat:
             sstat = os.lstat(src)
-    except Exception, e:
+    except Exception as e:
         print("movefile: Stating source file failed...", e)
         return None
 
             try:
                 os.unlink(dest)
                 destexists = 0
-            except Exception, e:
+            except Exception as e:
                 pass
 
     if stat.S_ISLNK(sstat[stat.ST_MODE]):
             #os.lchown(dest,sstat[stat.ST_UID],sstat[stat.ST_GID])
             os.unlink(src)
             return os.lstat(dest)
-        except Exception, e:
+        except Exception as e:
             print("movefile: failed to properly create symlink:", dest, "->", target, e)
             return None
 
         try:
             os.rename(src, dest)
             renamefailed = 0
-        except Exception, e:
+        except Exception as e:
             if e[0] != errno.EXDEV:
                 # Some random error.
                 print("movefile: Failed to move", src, "to", dest, e)
                 shutil.copyfile(src, dest + "#new")
                 os.rename(dest + "#new", dest)
                 didcopy = 1
-            except Exception, e:
+            except Exception as e:
                 print('movefile: copy', src, '->', dest, 'failed.', e)
                 return None
         else:
                 os.lchown(dest, sstat[stat.ST_UID], sstat[stat.ST_GID])
                 os.chmod(dest, stat.S_IMODE(sstat[stat.ST_MODE])) # Sticky is reset on chown
                 os.unlink(src)
-        except Exception, e:
+        except Exception as e:
             print("movefile: Failed to chown/chmod/unlink", dest, e)
             return None
 
     try:
         if not sstat:
             sstat = os.lstat(src)
-    except Exception, e:
+    except Exception as e:
         print("copyfile: Stating source file failed...", e)
         return False
 
             try:
                 os.unlink(dest)
                 destexists = 0
-            except Exception, e:
+            except Exception as e:
                 pass
 
     if stat.S_ISLNK(sstat[stat.ST_MODE]):
             os.symlink(target, dest)
             #os.lchown(dest,sstat[stat.ST_UID],sstat[stat.ST_GID])
             return os.lstat(dest)
-        except Exception, e:
+        except Exception as e:
             print("copyfile: failed to properly create symlink:", dest, "->", target, e)
             return False
 
         try: # For safety copy then move it over.
             shutil.copyfile(src, dest + "#new")
             os.rename(dest + "#new", dest)
-        except Exception, e:
+        except Exception as e:
             print('copyfile: copy', src, '->', dest, 'failed.', e)
             return False
     else:
     try:
         os.lchown(dest, sstat[stat.ST_UID], sstat[stat.ST_GID])
         os.chmod(dest, stat.S_IMODE(sstat[stat.ST_MODE])) # Sticky is reset on chown
-    except Exception, e:
+    except Exception as e:
         print("copyfile: Failed to chown/chmod/unlink", dest, e)
         return False