def compile_pycos(toc):
    """Given a TOC or equivalent list of tuples, generates all the required
    pyc/pyo files, writing in a local directory if required, and returns the
    list of tuples with the updated pathnames.
    """
    global BUILDPATH

    # For those modules that need to be rebuilt, use the build directory
    # PyInstaller creates during the build process.
    basepath = os.path.join(BUILDPATH, "localpycos")

    new_toc = []
    for (nm, fnm, typ) in toc:

        # Trim the terminal "c" or "o"
        source_fnm = fnm[:-1]

        # If the source is newer than the compiled, or the compiled doesn't
        # exist, we need to perform a build ourselves.
        if mtime(source_fnm) > mtime(fnm):
            try:
                py_compile.compile(source_fnm)
            except IOError:
                # If we're compiling on a system directory, probably we don't
                # have write permissions; thus we compile to a local directory
                # and change the TOC entry accordingly.
                ext = os.path.splitext(fnm)[1]

                if "__init__" not in fnm:
                    # If it's a normal module, use last part of the qualified
                    # name as module name and the first as leading path
                    leading, mod_name = nm.split(".")[:-1], nm.split(".")[-1]
                else:
                    # In case of a __init__ module, use all the qualified name
                    # as leading path and use "__init__" as the module name
                    leading, mod_name = nm.split("."), "__init__"

                leading = os.path.join(basepath, *leading)

                if not os.path.exists(leading):
                    os.makedirs(leading)

                fnm = os.path.join(leading, mod_name + ext)
                py_compile.compile(source_fnm, fnm)

        new_toc.append((nm, fnm, typ))

    return new_toc
Given a TOC or equivalent list of tuples, generates all the required
    pyc/pyo files, writing in a local directory if required, and returns the
    list of tuples with the updated pathnames.