Repository: linkedin/shiv

Issue:
The "create a pyz of shiv using shiv" example doesn't work
As written, the example leaves the shiv pyz file with a shebang pointing at the (presumably temporary) virtual environment used to build it.

The example should probably include a `-p "/usr/bin/env python3"` argument to specify an explicit interpreter.

Actually, given that shiv pyz files are self-contained, there's no real benefit to them ever having shebangs that refer to a virtualenv - maybe it would be worth making the default shebang `/usr/bin/env python3`, or at least locate the "base" Python interpreter for a virtualenv - which can be done as

```python
Path(getattr(sys, 'real_prefix', sys.base_prefix)) / Path(sys.executable).relative_to(sys.prefix)
```

Comments:

Patch:
diff --git a/README.md b/README.md
index 831be3b..656dfb2 100644
--- a/README.md
+++ b/README.md
@@ -69,8 +69,8 @@ pip install shiv
 You can even create a pyz _of_ shiv _using_ shiv!
 
 ```sh
-python3 -m venv shiv
-source shiv/bin/activate
+python3 -m venv .
+source bin/activate
 pip install shiv
 shiv -c shiv -o shiv shiv
 ```
diff --git a/src/shiv/bootstrap/__init__.py b/src/shiv/bootstrap/__init__.py
index 6c2989b..52558a0 100644
--- a/src/shiv/bootstrap/__init__.py
+++ b/src/shiv/bootstrap/__init__.py
@@ -123,7 +123,7 @@ def bootstrap():
         mod = import_string(env.entry_point)
         try:
             sys.exit(mod())
-        except TypeError as e:
+        except TypeError:
             # catch "<module> is not callable", which is thrown when the entry point's
             # callable shares a name with it's parent module
             # e.g. "from foo.bar import bar; bar()"
diff --git a/src/shiv/cli.py b/src/shiv/cli.py
index 27010cc..ec97dea 100644
--- a/src/shiv/cli.py
+++ b/src/shiv/cli.py
@@ -26,7 +26,7 @@ from .constants import (
     NO_ENTRY_POINT,
 )
 
-__version__ = '0.0.36'
+__version__ = "0.0.36"
 
 # This is the 'knife' emoji
 SHIV = u"\U0001F52A"
@@ -42,6 +42,7 @@ def find_entry_point(site_packages: Path, console_script: str) -> str:
     :param site_packages: A path to a site-packages directory on disk.
     :param console_script: A console_script string.
     """
+
     config_parser = ConfigParser()
     config_parser.read(site_packages.rglob("entry_points.txt"))
     return config_parser["console_scripts"][console_script]
@@ -55,18 +56,52 @@ def copy_bootstrap(bootstrap_target: Path) -> None:
 
     :param bootstrap_target: The temporary directory where we are staging pyz contents.
     """
+
     for bootstrap_file in importlib_resources.contents(bootstrap):
         if importlib_resources.is_resource(bootstrap, bootstrap_file):
             with importlib_resources.path(bootstrap, bootstrap_file) as f:
                 shutil.copyfile(f.absolute(), bootstrap_target / f.name)
 
 
+def _interpreter_path(append_version: bool = False) -> str:
+    """A function to return the path to the current Python interpreter.
+
+    Even when inside a venv, this will return the interpreter the venv was created with.
+
+    """
+
+    base_dir = Path(getattr(sys, "real_prefix", sys.base_prefix)).resolve()
+    sys_exec = Path(sys.executable)
+    name = sys_exec.stem
+    suffix = sys_exec.suffix
+
+    if append_version:
+        name += str(sys.version_info.major)
+
+    name += suffix
+
+    try:
+        return str(next(iter(base_dir.rglob(name))))
+
+    except StopIteration:
+
+        if not append_version:
+            # If we couldn't find an interpreter, it's likely that we looked for
+            # "python" when we should've been looking for "python3"
+            # so we try again with append_version=True
+            return _interpreter_path(append_version=True)
+
+        # If we were still unable to find a real interpreter for some reason
+        # we fallback to the current runtime's interpreter
+        return sys.executable
+
+
 @click.command(
     context_settings=dict(
         help_option_names=["-h", "--help", "--halp"], ignore_unknown_options=True
     )
 )
-@click.version_option(version=__version__, prog_name='shiv')
+@click.version_option(version=__version__, prog_name="shiv")
 @click.option("--entry-point", "-e", default=None, help="The entry point to invoke.")
 @click.option(
     "--console-script", "-c", default=None, help="The console_script to invoke."
@@ -103,7 +138,8 @@ def main(
     Shiv is a command line utility for building fully self-contained Python zipapps
     as outlined in PEP 441, but with all their dependencies included!
     """
-    quiet = "-q" in pip_args or '--quiet' in pip_args
+
+    quiet = "-q" in pip_args or "--quiet" in pip_args
 
     if not quiet:
         click.secho(" shiv! " + SHIV, bold=True)
@@ -158,8 +194,8 @@ def main(
         # create the zip
         builder.create_archive(
             Path(working_path),
-            target=Path(output_file),
-            interpreter=python or sys.executable,
+            target=Path(output_file).expanduser(),
+            interpreter=python or _interpreter_path(),
             main="_bootstrap:bootstrap",
             compressed=compressed,
         )


Test patch:
diff --git a/test/test_cli.py b/test/test_cli.py
index 30cd78b..3e469cc 100644
--- a/test/test_cli.py
+++ b/test/test_cli.py
@@ -8,7 +8,7 @@ import pytest
 
 from click.testing import CliRunner
 
-from shiv.cli import main
+from shiv.cli import main, _interpreter_path
 from shiv.constants import DISALLOWED_PIP_ARGS, NO_PIP_ARGS_OR_SITE_PACKAGES, NO_OUTFILE, BLACKLISTED_ARGS
 
 
@@ -31,6 +31,11 @@ class TestCLI:
         assert result.exit_code == 1
         assert strip_header(result.output) == NO_OUTFILE
 
+    def test_find_interpreter(self):
+        interpreter = _interpreter_path()
+        assert Path(interpreter).exists()
+        assert Path(interpreter).is_file()
+
     @pytest.mark.parametrize("arg", [arg for tup in BLACKLISTED_ARGS.keys() for arg in tup])
     def test_blacklisted_args(self, runner, arg):
         result = runner(['-o', 'tmp', arg])