问题描述
我来自 Java 背景,对 Python 完全陌生.
I am coming from Java background and completely new at Python.
现在我有一个包含一些导入的 Python 文件的小项目.我知道我的计算机上没有安装导入的依赖项,所以我尝试找出所需的依赖项并运行 pip
来安装它们.
Now I have got a small project with a few Python files that contain a few imports. I know I does not have the imported dependencies installed on my computer, so I try to figure out the required dependencies and run pip
to install them.
我想以不同的方式来做.我更愿意将依赖项列在一个文件中,并在构建过程中自动安装它们.
I would like to do it differently. I would prefer to have the dependencies listed in a single file and install them automatically during the build process.
有意义吗?如果是的话,我有几个问题:
Does it make sense ? If it does I have a few questions:
- 如何列出
pip
需要安装的项目依赖? - 如何运行
pip
来安装列表中的依赖项?
- How to list the project dependencies required to install by
pip
? - How to run
pip
to install the dependencies from the list ?
推荐答案
管理 Python 项目依赖项的常用方法是通过项目根目录中名为requirements.txt"的文件.一个简单的方法是:
A common way to manage dependencies for a python project is via a file in root of the project named "requirements.txt". An easy way to make this is:
- 为您的项目设置一个 python virtualenv
- 通过 pip 手动安装所需的模块
- 执行
pip freeze >requirements.txt
生成需求文件
- Setup a python virtualenv for your project
- Manually install the required modules via pip
- Execute
pip freeze > requirements.txt
to generate the requirements file
然后您可以使用 pip install -r requirements.txt
在其他位置安装所有依赖项.
You can then install all the dependencies in other locations using pip install -r requirements.txt
.
如果你想在其他人pip install
你的包时自动安装依赖,你可以在你的setup.py
中使用install_requires()
>.
If you want dependencies to be installed automatically when other people pip install
your package, you can use install_requires()
in your setup.py
.
这篇关于Python 项目的简单依赖管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!