chore: 开发脚本自动进入虚拟环境

This commit is contained in:
Nixevol
2026-07-13 16:28:08 +08:00
parent 182f0e5612
commit 3c74f03e7e
4 changed files with 57 additions and 10 deletions
+6 -6
View File
@@ -7,16 +7,16 @@
首次运行前:
```bash
python -m venv .venv
.\.venv\Scripts\activate
python -m pip install -r scripts/requirements.txt
python scripts/dev.py --install
python scripts/dev.py
```
如果 PowerShell 阻止激活脚本,可在当前终端临时放行后再激活:
`dev.py` 会先检查当前 Python 是否已在虚拟环境中;若没有,会自动复用项目根目录的 `.venv`/`venv`;若两者都不存在,会创建 `.venv` 并安装 `scripts/requirements.txt`,随后用虚拟环境 Python 重新执行当前命令。
```bash
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
.\.venv\Scripts\activate
python scripts/dev.py --install # 首次:安装 pnpm 依赖 + 启动
python scripts/dev.py --no-seed # 跳过种子数据
python scripts/dev.py --install-mode # 调试首次安装向导
```
| 脚本 | 作用 |
+44
View File
@@ -26,12 +26,56 @@
"""
from __future__ import annotations
import os
import re
import subprocess
import sys
import threading
import time
from pathlib import Path
ROOT_DIR = Path(__file__).resolve().parent.parent
def in_virtualenv() -> bool:
return (
bool(os.environ.get("VIRTUAL_ENV"))
or sys.prefix != getattr(sys, "base_prefix", sys.prefix)
or hasattr(sys, "real_prefix")
)
def venv_python(venv_dir: Path) -> Path:
return venv_dir / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
def ensure_virtualenv() -> None:
"""Re-run dev.py inside the project virtualenv before importing script dependencies."""
if in_virtualenv() or os.environ.get("ARTVERIS_SKIP_VENV") == "1":
return
existing = next(
(path for path in (ROOT_DIR / ".venv", ROOT_DIR / "venv") if venv_python(path).exists()),
None,
)
venv_dir = existing or (ROOT_DIR / ".venv")
created = existing is None
if existing is None:
print(f"[artveris] 未检测到虚拟环境,正在创建 {venv_dir} ...")
subprocess.run([sys.executable, "-m", "venv", str(venv_dir)], cwd=str(ROOT_DIR), check=True)
python = venv_python(venv_dir)
requirements = ROOT_DIR / "scripts" / "requirements.txt"
if created and requirements.exists():
print(f"[artveris] 使用虚拟环境安装脚本依赖:{requirements}")
subprocess.run([str(python), "-m", "pip", "install", "-r", str(requirements)], cwd=str(ROOT_DIR), check=True)
print(f"[artveris] 切换到虚拟环境 Python:{python}")
os.execv(str(python), [str(python), str(Path(__file__).resolve()), *sys.argv[1:]])
ensure_virtualenv()
from _lib import (
ROOT,
create_kill_job,