# Buggy code
def _spawn_from_binary_external(cls, binary):
    def create_interpreter(stdout, check_binary=False):
        identity = stdout.decode("utf-8").strip()
        if not identity:
            raise cls.IdentificationError(
                "Could not establish identity of {}.".format(binary)
            )
        interpreter = cls(PythonIdentity.decode(identity))
        # We should not need to check this since binary == interpreter.binary should always be
        # true, but historically this could be untrue as noted in `PythonIdentity.get`.
        if check_binary and not os.path.exists(interpreter.binary):
            raise cls.InterpreterNotFound(
                "Cached interpreter for {} reports a binary of {}, which could not be found".format(
                    binary, interpreter.binary
                )
            )
        return interpreter

    # Part of the PythonInterpreter data are environment markers that depend on the current OS
    # release. That data can change when the OS is upgraded but (some of) the installed interpreters
    # remain the same. As such, include the OS in the hash structure for cached interpreters.
    os_digest = hashlib.sha1()
    for os_identifier in platform.release(), platform.version():
        os_digest.update(os_identifier.encode("utf-8"))
    os_hash = os_digest.hexdigest()

    interpreter_cache_dir = os.path.join(ENV.PEX_ROOT, "interpreters")
    os_cache_dir = os.path.join(interpreter_cache_dir, os_hash)
    if os.path.isdir(interpreter_cache_dir) and not os.path.isdir(os_cache_dir):
        with TRACER.timed("GCing interpreter cache from prior OS version"):
            safe_rmtree(interpreter_cache_dir)

    interpreter_hash = CacheHelper.hash(binary)

    # Some distributions include more than one copy of the same interpreter via a hard link (e.g.:
    # python3.7 is a hardlink to python3.7m). To ensure a deterministic INTERP-INFO file we must
    # emit a separate INTERP-INFO for each link since INTERP-INFO contains the interpreter path and
    # would otherwise be unstable.
    #
    # See cls._REGEXEN for a related affordance.
    #
    # N.B.: The path for --venv mode interpreters can be quite long; so we just used a fixed
    # length hash of the interpreter binary path to ensure uniqueness and not run afoul of file
    # name length limits.
    path_id = hashlib.sha1(binary.encode("utf-8")).hexdigest()

    cache_dir = os.path.join(os_cache_dir, interpreter_hash, path_id)
    cache_file = os.path.join(cache_dir, cls.INTERP_INFO_FILE)
    if os.path.isfile(cache_file):
        try:
            with open(cache_file, "rb") as fp:
                return SpawnedJob.completed(
                    create_interpreter(fp.read(), check_binary=True)
                )
        except (IOError, OSError, cls.Error, PythonIdentity.Error):
            safe_rmtree(cache_dir)
            return cls._spawn_from_binary_external(binary)
    else:
        pythonpath = third_party.expose(["pex"])
        cmd, env = cls._create_isolated_cmd(
            binary,
            args=[
                "-c",
                dedent(
                    """\
                        import os
                        import sys

                        from pex.common import atomic_directory, safe_open
                        from pex.interpreter import PythonIdentity


                        encoded_identity = PythonIdentity.get(binary={binary!r}).encode()
                        sys.stdout.write(encoded_identity)
                        with atomic_directory({cache_dir!r}, exclusive=False) as cache_dir:
                            if cache_dir:
                                with safe_open(os.path.join(cache_dir, {info_file!r}), 'w') as fp:
                                    fp.write(encoded_identity)
                        """.format(
                        binary=binary,
                        cache_dir=cache_dir,
                        info_file=cls.INTERP_INFO_FILE,
                    )
                ),
            ],
            pythonpath=pythonpath,
        )
        process = Executor.open_process(
            cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE
        )
        job = Job(command=cmd, process=process)
        return SpawnedJob.stdout(job, result_func=create_interpreter)


# Traceback (pex.jobs.Error)
$ python3.8 -mvenv venv
$ venv/bin/pip -q install -U pip
$ venv/bin/pip -q install pex
$ venv/bin/pex --version
2.1.30
$ venv/bin/pip -q install --target dir pex==2.1.16
$ ls dir/
bin  pex  pex-2.1.16.dist-info
$ venv/bin/pex isort -c isort -o dir/isort.pex
$ cd dir/
dir $ rm -rf ~/.pex/interpreters/
dir $ ./isort.pex


_                 _
(_) ___  ___  _ __| |_
| |/ _/ / _ \/ '__  _/
| |\__ \/\_\/| |  | |_
|_|\___/\___/\_/   \_/

isort your imports, so you don't have to.

VERSION 5.7.0


Nothing to do: no files or paths have have been passed in!

Try one of the following:

`isort .` - sort all Python files, starting from the current directory, recursively.
`isort . --interactive` - Do the same, but ask before making any changes.
`isort . --check --diff` - Check to see if imports are correctly sorted within this project.
`isort --help` - In-depth information about isort's available command-line options.

Visit https://pycqa.github.io/isort/ for complete information about how to use isort.

dir $ rm -rf ~/.pex/interpreters/
dir $ source ../venv/bin/activate
(venv) dir $ ./isort.pex
Traceback (most recent call last):
File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "./isort.pex/__main__.py", line 81, in <module>
File "/tmp/pex_ii_leak/dir/isort.pex/.bootstrap/pex/pex_bootstrapper.py", line 403, in bootstrap_pex
File "/tmp/pex_ii_leak/dir/isort.pex/.bootstrap/pex/pex_bootstrapper.py", line 305, in maybe_reexec_pex
File "/tmp/pex_ii_leak/dir/isort.pex/.bootstrap/pex/interpreter.py", line 922, in resolve_base_interpreter
File "/tmp/pex_ii_leak/dir/isort.pex/.bootstrap/pex/interpreter.py", line 710, in from_binary
File "/tmp/pex_ii_leak/dir/isort.pex/.bootstrap/pex/jobs.py", line 199, in await_result
File "/tmp/pex_ii_leak/dir/isort.pex/.bootstrap/pex/jobs.py", line 78, in communicate
File "/tmp/pex_ii_leak/dir/isort.pex/.bootstrap/pex/jobs.py", line 103, in _check_returncode
pex.jobs.Error: Executing /usr/bin/python3.8 -s -c import os
import sys

from pex.common import atomic_directory, safe_open
from pex.interpreter import PythonIdentity


encoded_identity = PythonIdentity.get(binary='/usr/bin/python3.8').encode()
sys.stdout.write(encoded_identity)
with atomic_directory('/home/jsirois/.pex/interpreters/f841ccf354cda73fa22fdf414a02f6c680c1b032/a65b2009934de8713e1f759d0553218a35dd5bfe/e90219f1da0abbc0e93646d91bc21868bc95a74d', exclusive=False) as cache_dir:
if cache_dir:
with safe_open(os.path.join(cache_dir, 'INTERP-INFO'), 'w') as fp:
fp.write(encoded_identity)
failed with 1
STDERR:
Traceback (most recent call last):
File "<string>", line 8, in <module>
TypeError: get() got an unexpected keyword argument 'binary'

# Fixed code
def _spawn_from_binary_external(cls, binary):
    def create_interpreter(stdout, check_binary=False):
        identity = stdout.decode("utf-8").strip()
        if not identity:
            raise cls.IdentificationError(
                "Could not establish identity of {}.".format(binary)
            )
        interpreter = cls(PythonIdentity.decode(identity))
        # We should not need to check this since binary == interpreter.binary should always be
        # true, but historically this could be untrue as noted in `PythonIdentity.get`.
        if check_binary and not os.path.exists(interpreter.binary):
            raise cls.InterpreterNotFound(
                "Cached interpreter for {} reports a binary of {}, which could not be found".format(
                    binary, interpreter.binary
                )
            )
        return interpreter

    # Part of the PythonInterpreter data are environment markers that depend on the current OS
    # release. That data can change when the OS is upgraded but (some of) the installed interpreters
    # remain the same. As such, include the OS in the hash structure for cached interpreters.
    os_digest = hashlib.sha1()
    for os_identifier in platform.release(), platform.version():
        os_digest.update(os_identifier.encode("utf-8"))
    os_hash = os_digest.hexdigest()

    interpreter_cache_dir = os.path.join(ENV.PEX_ROOT, "interpreters")
    os_cache_dir = os.path.join(interpreter_cache_dir, os_hash)
    if os.path.isdir(interpreter_cache_dir) and not os.path.isdir(os_cache_dir):
        with TRACER.timed("GCing interpreter cache from prior OS version"):
            safe_rmtree(interpreter_cache_dir)

    interpreter_hash = CacheHelper.hash(binary)

    # Some distributions include more than one copy of the same interpreter via a hard link (e.g.:
    # python3.7 is a hardlink to python3.7m). To ensure a deterministic INTERP-INFO file we must
    # emit a separate INTERP-INFO for each link since INTERP-INFO contains the interpreter path and
    # would otherwise be unstable.
    #
    # See cls._REGEXEN for a related affordance.
    #
    # N.B.: The path for --venv mode interpreters can be quite long; so we just used a fixed
    # length hash of the interpreter binary path to ensure uniqueness and not run afoul of file
    # name length limits.
    path_id = hashlib.sha1(binary.encode("utf-8")).hexdigest()

    cache_dir = os.path.join(os_cache_dir, interpreter_hash, path_id)
    cache_file = os.path.join(cache_dir, cls.INTERP_INFO_FILE)
    if os.path.isfile(cache_file):
        try:
            with open(cache_file, "rb") as fp:
                return SpawnedJob.completed(
                    create_interpreter(fp.read(), check_binary=True)
                )
        except (IOError, OSError, cls.Error, PythonIdentity.Error):
            safe_rmtree(cache_dir)
            return cls._spawn_from_binary_external(binary)
    else:
        pythonpath = third_party.expose(["pex"])
        cmd, env = cls._create_isolated_cmd(
            binary,
            args=[
                "-c",
                dedent(
                    """\
                        import os
                        import sys

                        from pex.common import atomic_directory, safe_open
                        from pex.interpreter import PythonIdentity


                        encoded_identity = PythonIdentity.get(binary={binary!r}).encode()
                        sys.stdout.write(encoded_identity)
                        with atomic_directory({cache_dir!r}, exclusive=False) as cache_dir:
                            if cache_dir:
                                with safe_open(os.path.join(cache_dir, {info_file!r}), 'w') as fp:
                                    fp.write(encoded_identity)
                        """.format(
                        binary=binary,
                        cache_dir=cache_dir,
                        info_file=cls.INTERP_INFO_FILE,
                    )
                ),
            ],
            pythonpath=pythonpath,
        )
        # Ensure the `.` implicit PYTHONPATH entry contains no Pex code (of a different version)
        # that might interfere with the behavior we expect in the script above.
        cwd = safe_mkdtemp()
        process = Executor.open_process(
            cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd
        )
        job = Job(command=cmd, process=process, finalizer=lambda: safe_rmtree(cwd))
        return SpawnedJob.stdout(job, result_func=create_interpreter)