Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically detect virtual environments when used via python -m uv #1504

Merged
merged 2 commits into from
Feb 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions python/uv/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,25 @@
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
venv_marker = os.path.join(sys.prefix, "pyvenv.cfg")

if os.path.exists(venv_marker):
return sys.prefix

return ""


def find_uv_bin() -> str:
"""Return the uv binary path."""

Expand Down Expand Up @@ -30,10 +49,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)