mirror of https://github.com/astral-sh/uv
Automatically detect virtual environments when used via `python -m uv` (#1504)
Closes https://github.com/astral-sh/uv/issues/1501
This commit is contained in:
parent
d5e8531ae3
commit
f87c29e326
|
|
@ -3,6 +3,25 @@ import sys
|
||||||
import sysconfig
|
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:
|
def find_uv_bin() -> str:
|
||||||
"""Return the uv binary path."""
|
"""Return the uv binary path."""
|
||||||
|
|
||||||
|
|
@ -30,10 +49,16 @@ def find_uv_bin() -> str:
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
uv = os.fsdecode(find_uv_bin())
|
uv = os.fsdecode(find_uv_bin())
|
||||||
|
|
||||||
|
env = {}
|
||||||
|
venv = detect_virtualenv()
|
||||||
|
if venv:
|
||||||
|
env["VIRTUAL_ENV"] = venv
|
||||||
|
|
||||||
if sys.platform == "win32":
|
if sys.platform == "win32":
|
||||||
import subprocess
|
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)
|
sys.exit(completed_process.returncode)
|
||||||
else:
|
else:
|
||||||
os.execvp(uv, [uv, *sys.argv[1:]])
|
os.execvpe(uv, [uv, *sys.argv[1:]], env=env)
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue