Skip to content

Instantly share code, notes, and snippets.

@bluss
Created June 21, 2023 19:14
Show Gist options
  • Save bluss/d5e7a1f439a193ca62777bfcfa9fe573 to your computer and use it in GitHub Desktop.
Save bluss/d5e7a1f439a193ca62777bfcfa9fe573 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
"""
Start a version sensitive ipython3 that also goes into "foreign" virtualenvs.
Rye-enabled ipython: an ipython that follows your pinned python version and is usable
in all rye managed projects.
"""
from pathlib import Path
import os
import shlex
import subprocess
import sys
# Will look for ipy3.10, ipy3.11 etc rye installs of ipython here
IPYTHON_INSTALL_BASE = "~/program"
def shell(cmd):
return subprocess.run(cmd, capture_output=True, check=True, encoding="utf-8")
def main():
cwd = Path(".")
venv = cwd / ".venv"
if not venv.exists():
venv = None
exec_path = None
# check venv for ipython
if venv:
venv_ipython = venv / "bin/ipython"
if venv_ipython.exists():
exec_path = venv_ipython
# check for global ipython installs
if not exec_path:
# Use python (Rye's python shim) to tell us which version to use
local_py_version = shell([
"python",
"-S",
"-c",
"import sys; print('.'.join(map(str, sys.version_info[:2])))"
]).stdout.strip()
ipython_install = Path(IPYTHON_INSTALL_BASE).expanduser() / ("ipy" + local_py_version)
if ipython_install.exists():
exec_path = ipython_install / ".venv/bin/ipython"
else:
print(f"IPython {local_py_version} not installed!", file=sys.stderr)
exec_path = "ipython"
commands = ""
if venv:
venv_activate = venv / "bin/activate"
commands += "source " + str(venv_activate)
commands += "\n"
args = list(sys.argv)
args[0] = str(exec_path)
commands += " ".join(shlex.quote(arg) for arg in args)
if venv:
print("Activating virtualenv", venv, "...", file=sys.stderr)
cmd = ["bash", "-c", commands]
os.execvp("bash", cmd)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment