# Buggy code
def demote_bootstrap(cls):
    TRACER.log("Bootstrap complete, performing final sys.path modifications...")

    bootstrap_path = __file__
    module_import_path = __name__.split(".")
    root_package = module_import_path[0]

    # For example, our __file__ might be requests.pex/.bootstrap/_pex/pex.pyc and our import path
    # _pex.pex; so we walk back through all the module components of our import path to find the
    # base sys.path entry where we were found (requests.pex/.bootstrap in this example).
    for _ in module_import_path:
        bootstrap_path = os.path.dirname(bootstrap_path)
    bootstrap_path_index = sys.path.index(bootstrap_path)

    # Move the third party resources pex uses to the end of sys.path for the duration of the run to
    # allow conflicting versions supplied by user dependencies to win during the course of the
    # execution of user code.
    for _, mod, _ in pkgutil.iter_modules([bootstrap_path]):
        if mod != root_package:  # We let _pex stay imported
            TRACER.log(
                "Un-importing third party bootstrap dependency %s from %s"
                % (mod, bootstrap_path)
            )
            sys.modules.pop(mod)
    sys.path.pop(bootstrap_path_index)
    sys.path.append(bootstrap_path)

    TRACER.log("PYTHONPATH contains:")
    for element in sys.path:
        TRACER.log("  %c %s" % (" " if os.path.exists(element) else "*", element))
    TRACER.log("  * - paths that do not exist or will be imported via zipimport")


# Traceback (ImportError)
~/sandbox $ . venv/bin/activate
(venv)  ~/sandbox $ python -V
Python 2.7.15
(venv)  ~/sandbox $ pex --version
pex 1.4.6
(venv)  ~/sandbox $ pex responses
Python 2.7.15 (default, May  1 2018, 16:44:08)
[GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
import responses
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/private/var/folders/mk/bz4w0f3505190h3n4x21_jlc0000gn/T/tmpReh1br/.deps/responses-0.9.0-py2.py3-none-any.whl/responses.py", line 41, in <module>
import mock as std_mock
File "/private/var/folders/mk/bz4w0f3505190h3n4x21_jlc0000gn/T/tmpReh1br/.deps/mock-2.0.0-py2.py3-none-any.whl/mock/__init__.py", line 2, in <module>
import mock.mock as _mock
File "/private/var/folders/mk/bz4w0f3505190h3n4x21_jlc0000gn/T/tmpReh1br/.deps/mock-2.0.0-py2.py3-none-any.whl/mock/mock.py", line 71, in <module>
_v = VersionInfo('mock').semantic_version()
File "/private/var/folders/mk/bz4w0f3505190h3n4x21_jlc0000gn/T/tmpReh1br/.deps/pbr-4.2.0-py2.py3-none-any.whl/pbr/version.py", line 462, in semantic_version
self._semantic = self._get_version_from_pkg_resources()
File "/private/var/folders/mk/bz4w0f3505190h3n4x21_jlc0000gn/T/tmpReh1br/.deps/pbr-4.2.0-py2.py3-none-any.whl/pbr/version.py", line 439, in _get_version_from_pkg_resources
import pkg_resources
File "/private/var/folders/mk/bz4w0f3505190h3n4x21_jlc0000gn/T/tmpReh1br/.bootstrap/pkg_resources/__init__.py", line 77, in <module>
from . import py31compat
ImportError: cannot import name py31compat

# Fixed code
def demote_bootstrap(cls):
    TRACER.log("Bootstrap complete, performing final sys.path modifications...")

    bootstrap_path = __file__
    module_import_path = __name__.split(".")
    root_package = module_import_path[0]

    # For example, our __file__ might be requests.pex/.bootstrap/_pex/pex.pyc and our import path
    # _pex.pex; so we walk back through all the module components of our import path to find the
    # base sys.path entry where we were found (requests.pex/.bootstrap in this example).
    for _ in module_import_path:
        bootstrap_path = os.path.dirname(bootstrap_path)
    bootstrap_path_index = sys.path.index(bootstrap_path)

    # Move the third party resources pex uses to the end of sys.path for the duration of the run to
    # allow conflicting versions supplied by user dependencies to win during the course of the
    # execution of user code.
    for _, mod, _ in pkgutil.iter_modules([bootstrap_path]):
        if mod != root_package:  # We let _pex stay imported
            TRACER.log(
                "Un-importing third party bootstrap dependency %s from %s"
                % (mod, bootstrap_path)
            )
            sys.modules.pop(mod)
            submod_prefix = mod + "."
            for submod in [
                m for m in sys.modules.keys() if m.startswith(submod_prefix)
            ]:
                sys.modules.pop(submod)
    sys.path.pop(bootstrap_path_index)
    sys.path.append(bootstrap_path)

    TRACER.log("PYTHONPATH contains:")
    for element in sys.path:
        TRACER.log("  %c %s" % (" " if os.path.exists(element) else "*", element))
    TRACER.log("  * - paths that do not exist or will be imported via zipimport")