简体   繁体   English

在新的 Python 虚拟环境中持续安装模块

[英]Persisting module installation across new python virtual environments

For background, I work mostly in the terminal and edit code using vim.对于背景,我主要在终端工作并使用 vim 编辑代码。 For long-term python projects I manage venvs and lock files in source control using poetry.对于长期的 Python 项目,我使用诗歌管理 venvs 并在源代码控制中锁定文件。

There are some modules I like to have installed in almost every venv I work in, such as ipython/ptpython, (pytest-)icdiff, and other "quality of life" extensions that I need not foist on project collaborators who don't use my workflow.我喜欢在我工作的几乎每个 venv 中安装一些模块,例如 ipython/ptpython、(pytest-)icdiff 和其他“生活质量”扩展,我不需要强加给不使用的项目合作者我的工作流程。 I can install ptpython in the global scope using my distro's package manager (or pipx), but then when I run it, it does not run inside the local venv and local dependencies are not accessible.我可以使用发行版的包管理器(或 pipx)在全局范围内安装 ptpython,但是当我运行它时,它不会在本地 venv 内运行,并且本地依赖项无法访问。 This gets obnoxious since I'm periodically recreating venvs as the lock files change.这变得令人讨厌,因为我会在锁定文件更改时定期重新创建 venv。 Right now I have a shell script that installs the things, but that feels like a hack.现在我有一个 shell 脚本来安装这些东西,但这感觉就像一个黑客。

An ideal solution might be a way to create something like a venv template, similar to the git templatedir option.一个理想的解决方案可能是创建类似 venv 模板的方法,类似于 git templatedir 选项。 Is there anything of such for Python? Python 有这样的东西吗?

The virtualenv module has an option to include system site packages in the venv: virtualenv 模块可以选择在 venv 中包含系统站点包:

python3 -m venv --system-site-packages .venv

There is a feature request to have support for this option added to poetry.有一个功能要求将此选项添加到诗歌中。

There is a nice overview of site packages in this thread .这个线程中有一个很好的站点包概述。

This doesn't directly answer maybe but I think anaconda environments are the way to go.这并没有直接回答也许,但我认为 anaconda 环境是要走的路。 You could create different 'base' environments, then clone them.您可以创建不同的“基础”环境,然后克隆它们。 Then you could add more packages using pip as you'd like on the new cloned environment, thereby not changing the base, but having customizability over new enviroment.然后,您可以根据需要在新的克隆环境中使用 pip 添加更多包,从而不更改基础,而是在新环境中具有可定制性。

Try this answer: https://stackoverflow.com/a/40702703/7654532试试这个答案: https : //stackoverflow.com/a/40702703/7654532

Solution解决方案

This problem isn't specific to Python venv, it's present in rvm and nvm also.这个问题不是 Python venv 特有的,它也存在于 rvm 和 nvm 中。 Just install the package under the global Python namespace and add it to your PYTHONPATH so that if the package isn't installed in the local repository Python falls back to your global Python namespace without modifying the repository lockfile.只需将包安装在全局 Python 命名空间下并将其添加到您的PYTHONPATH这样如果该包未安装在本地存储库中,Python 就会回退到您的全局 Python 命名空间,而无需修改存储库锁定文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM