Skip to content

Instantly share code, notes, and snippets.

@brettcannon
Created November 20, 2025 18:19
Show Gist options
  • Select an option

  • Save brettcannon/fcbb07786709ff7ea97b5298f99f196f to your computer and use it in GitHub Desktop.

Select an option

Save brettcannon/fcbb07786709ff7ea97b5298f99f196f to your computer and use it in GitHub Desktop.
Python Launcher for Unix rewrite in pure Python PoC
import os
import sys
def activated_venv():
"""Check if a virtual environment is activated."""
if "VIRTUAL_ENV" not in os.environ:
return None
os.path.join(os.environ["VIRTUAL_ENV"], "bin", "python")
def preexisting_venv():
"""Check if a virtual environment already exists."""
working_dir = os.getcwd()
while True:
venv_path = os.path.join(working_dir, ".venv", "bin", "python")
if os.path.exists(venv_path):
return venv_path
parent_dir = os.path.dirname(working_dir)
if parent_dir == working_dir:
break
else:
working_dir = parent_dir
MIN_FILE_LENGTH = len("python3.0")
def _key(python):
dir, item = python
version_str = item.removeprefix("python")
major, _, minor = version_str.partition('.')
try:
major = int(major)
except ValueError:
return -1, -1
try:
minor = int(minor)
except ValueError:
return -1, -1
return major, minor
def path():
"""Search $PATH for the newest Python interpreter."""
pythons = []
for dir in os.environ["PATH"].split(os.pathsep):
if not os.path.exists(dir):
continue
pythons.extend([(dir, item)
for item in os.listdir(dir)
if len(item)>=MIN_FILE_LENGTH and item.startswith("python") and '.' in item])
newest_python = max(pythons, key=_key)
return os.path.join(*newest_python)
def exec_(python_path):
"""Execute the found Python interpreter."""
args = sys.argv[1:]
os.execv(python_path, [python_path, *args])
if __name__ == "__main__":
if (python_path := activated_venv()) is None:
if (python_path := preexisting_venv()) is None:
if (python_path := path()) is None:
raise RuntimeError("No Python interpreter found.")
exec_(python_path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment