如何配置Python venv,使其激活时自动安装requirements.txt依赖
实现Python虚拟环境激活时自动安装依赖的跨平台方案
核心思路
不用手动逐个修改不同平台的激活文件,而是写一个通用的Python脚本处理依赖安装,再让所有激活文件统一调用这个脚本,一次配置就能覆盖全平台场景。
步骤1:创建通用的依赖安装脚本
在项目根目录新建install_requirements.py,内容如下:
import subprocess import sys from pathlib import Path def main(): requirements_path = Path(__file__).parent / "requirements.txt" if not requirements_path.exists(): print("requirements.txt不存在,跳过依赖安装", file=sys.stderr) return # 调用当前激活环境的pip安装依赖 subprocess.run( [sys.executable, "-m", "pip", "install", "-r", str(requirements_path)], check=False ) if __name__ == "__main__": main()
这个脚本会自动定位项目根目录的requirements.txt,用当前激活环境的pip执行安装,不受操作系统限制。
步骤2:修改所有激活文件,添加脚本调用命令
Linux/macOS(bash/zsh环境)
编辑venv/bin/activate,在文件末尾追加:
# 自动安装requirements.txt依赖 python "$(dirname "$0")/../install_requirements.py"
Windows(CMD环境)
编辑venv/Scripts/activate.bat,在文件末尾追加:
:: 自动安装requirements.txt依赖 python "%~dp0..\install_requirements.py"
Windows(PowerShell环境)
编辑venv/Scripts/Activate.ps1,在文件末尾追加:
# 自动安装requirements.txt依赖 python (Join-Path $PSScriptRoot "..\install_requirements.py")
Linux/macOS(csh/fish环境)
- 编辑
venv/bin/activate.csh,末尾追加:python "$(dirname $0)/../install_requirements.py" - 编辑
venv/bin/activate.fish,末尾追加:python (dirname (status filename))/../install_requirements.py
偷懒方案:批量修改所有激活文件
如果嫌手动逐个修改麻烦,可运行以下脚本一次性处理所有存在的激活文件:
from pathlib import Path venv_dir = Path("venv") install_script_path = Path(__file__).parent / "install_requirements.py" relative_path = install_script_path.relative_to(venv_dir.parent) # 定义各平台激活文件的追加内容 activation_files = [ (venv_dir / "bin" / "activate", f'python "$(dirname "$0")/../{relative_path}"'), (venv_dir / "Scripts" / "activate.bat", f'python "%~dp0..\\{relative_path.as_posix().replace("/", "\\\\")}"'), (venv_dir / "Scripts" / "Activate.ps1", f'python (Join-Path $PSScriptRoot "..\\{relative_path.as_posix().replace("/", "\\\\")}")'), (venv_dir / "bin" / "activate.csh", f'python "$(dirname $0)/../{relative_path}"'), (venv_dir / "bin" / "activate.fish", f'python (dirname (status filename))/../{relative_path}'), ] for file_path, command in activation_files: if file_path.exists(): with open(file_path, "a", encoding="utf-8") as f: f.write(f"\n# 自动安装requirements.txt依赖\n{command}\n") print(f"已修改 {file_path}")
可选优化:避免重复安装
如果不想每次激活都检查依赖,可给install_requirements.py加个标记文件逻辑,安装一次后就跳过后续检测:
# 在main函数开头添加 marker_file = Path(__file__).parent / ".requirements_installed" if marker_file.exists(): return # 在subprocess.run执行完成后添加 marker_file.touch()
内容的提问来源于stack exchange,提问作者DarkTrick
相关产品推荐
相关产品推荐

