From 967188a914df3461b92de27e9b9234fd8c22be85 Mon Sep 17 00:00:00 2001 From: Zanie Date: Fri, 16 Feb 2024 09:48:27 -0600 Subject: [PATCH 1/2] Automatically detect virtual environments when used via `python -m uv` --- python/uv/__main__.py | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/python/uv/__main__.py b/python/uv/__main__.py index 5fea6a3e73e9..ce2cf335626e 100644 --- a/python/uv/__main__.py +++ b/python/uv/__main__.py @@ -3,6 +3,26 @@ import sysconfig +def detect_virtualenv() -> str: + """ + Find the virtual environment path for the current Python executable. + """ + + # If it's already set, then just use it + value = os.getenv("VIRTUAL_ENV") + if value: + return value + + # Otherwise, check if we're in a venv + maybe_venv_dir = os.path.dirname(os.path.dirname(sys.executable)) + venv_marker = os.path.join(maybe_venv_dir, "pyvenv.cfg") + + if os.path.exists(venv_marker): + return maybe_venv_dir + + return "" + + def find_uv_bin() -> str: """Return the uv binary path.""" @@ -30,10 +50,16 @@ def find_uv_bin() -> str: if __name__ == "__main__": uv = os.fsdecode(find_uv_bin()) + + env = {} + venv = detect_virtualenv() + if venv: + env["VIRTUAL_ENV"] = venv + if sys.platform == "win32": import subprocess - completed_process = subprocess.run([uv, *sys.argv[1:]]) + completed_process = subprocess.run([uv, *sys.argv[1:]], env=env) sys.exit(completed_process.returncode) else: - os.execvp(uv, [uv, *sys.argv[1:]]) + os.execvpe(uv, [uv, *sys.argv[1:]], env=env) From a2da42fa56affd29a7a36ad70e1261f68702e293 Mon Sep 17 00:00:00 2001 From: Zanie Date: Fri, 16 Feb 2024 10:22:08 -0600 Subject: [PATCH 2/2] Use `sys.prefix` --- python/uv/__main__.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/python/uv/__main__.py b/python/uv/__main__.py index ce2cf335626e..975a72941b0a 100644 --- a/python/uv/__main__.py +++ b/python/uv/__main__.py @@ -14,11 +14,10 @@ def detect_virtualenv() -> str: return value # Otherwise, check if we're in a venv - maybe_venv_dir = os.path.dirname(os.path.dirname(sys.executable)) - venv_marker = os.path.join(maybe_venv_dir, "pyvenv.cfg") + venv_marker = os.path.join(sys.prefix, "pyvenv.cfg") if os.path.exists(venv_marker): - return maybe_venv_dir + return sys.prefix return ""