列出 Python 中的依赖项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42237072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List dependencies in Python
提问by RolfBly
What is the most efficient way to list all dependencies required to deploy a working project elsewhere (on a different OS, say)?
列出在其他地方(例如,在不同的操作系统上)部署工作项目所需的所有依赖项的最有效方法是什么?
Python 2.7, Windows dev environment, not using a virtualenv per project, but a global dev environment, installing libraries as needed, happily hopping from one project to the next.
Python 2.7,Windows 开发环境,不是每个项目都使用一个 virtualenv,而是一个全局开发环境,根据需要安装库,愉快地从一个项目跳到下一个项目。
I've kept track of most (not sure all) libraries I had to install for a given project. I have notkept track of any sub-dependencies that came auto-installed with them. Doing pip freeze
lists both, plus all the other libraries that were ever installed.
我一直跟踪我必须为给定项目安装的大多数(不确定所有)库。我没有跟踪随它们自动安装的任何子依赖项。Doingpip freeze
列出了两者,以及曾经安装过的所有其他库。
Is there a way to list what you need to install, no more, no less, to deploy the project?
有没有办法列出您需要安装的东西,不多也不少,以部署项目?
EDITIn view of the answers below, some clarification. My project consists of a bunch of modules (that I wrote), each with a bunch of import
s. Should I just copy-paste all the imports from all modules into a single file, sort eliminating duplicates, and throw out all from the standard library (and how do I know they are)? Or is there a better way? That's the question.
编辑鉴于下面的答案,一些澄清。我的项目由一堆模块(我写的)组成,每个模块都有一堆import
s。我是否应该将所有模块的所有导入复制粘贴到一个文件中,排序消除重复项,然后从标准库中删除所有内容(我怎么知道它们是)?或者,还有更好的方法?这就是问题所在。
采纳答案by 9000
Scan your import
statements. Chances are you only import things you explicitly wanted to import, and not the dependencies.
扫描你的import
陈述。您可能只导入您明确想要导入的内容,而不是依赖项。
Make a list like the one pip freeze
does, then create and activate a virtualenv.
像这样pip freeze
创建一个列表,然后创建并激活一个 virtualenv。
Do pip install -r your_list
, and try to run your code in that virtualenv. Heed any ImportError
exceptions, match them to packages, and add to your list. Repeat until your code runs without problems.
做pip install -r your_list
,并尝试在该 virtualenv 中运行您的代码。注意任何ImportError
例外情况,将它们与包匹配,然后添加到您的列表中。重复直到您的代码运行没有问题。
Now you have a list to feed to pip install
on your deployment site.
现在,您pip install
在部署站点上有一个要提供给的列表。
This is extremely manual, but requires no external tools, and forces you to make sure that your code runs. (Running your test suite as a check is great but not sufficient.)
这是非常手动的,但不需要外部工具,并强制您确保代码运行。(运行测试套件作为检查很好,但还不够。)
回答by Haifeng Zhang
pipreqs
solves the problem. It generates project-levelrequirement.txt file.
pipreqs
解决了这个问题。它生成项目级的requirement.txt 文件。
Install pipreqs: pip install pipreqs
安装pipreq: pip install pipreqs
- Generate project-level requirement.txt file:
pipreqs /path/to/your/project/
- requirements file would be saved in /path/to/your/project/requirements.txt
- 生成项目级的requirement.txt文件:
pipreqs /path/to/your/project/
- 需求文件将保存在 /path/to/your/project/requirements.txt
If you want to read more advantages of pipreqs
over pip freeze
, read it from here
如果您想阅读pipreqs
over 的更多优点pip freeze
,请从此处阅读
回答by Venu Gopal Tewari
On your terminal type:
在您的终端类型上:
pip install pipdeptree
cd <your project root>
pipdeptree
回答by nighthawk454
The way to do this is analyze your imports. To automate that, check out Snakefood. Then you can make a requirements.txt
file and get on your way to using virtualenv
.
这样做的方法是分析您的进口。要自动执行此操作,请查看Snakefood。然后你可以制作一个requirements.txt
文件并开始使用virtualenv
.
The following will list the dependencies, excluding modules from the standard library:
以下将列出依赖项,不包括标准库中的模块:
sfood -fuq package.py | sfood-filter-stdlib | sfood-target-files
Related questions:
相关问题:
Get a list of python packages used by a Django Project
回答by stemboy400
I would just run something like this:
我只想运行这样的东西:
import importlib
import os
import pathlib
import re
import sys, chardet
from sty import fg
sys.setrecursionlimit(100000000)
dependenciesPaths = list()
dependenciesNames = list()
paths = sys.path
red = fg(255, 0, 0)
green = fg(0, 200, 0)
end = fg.rs
def main(path):
try:
print("Finding imports in '" + path + "':")
file = open(path)
contents = file.read()
wordArray = re.split(" |\n", contents)
currentList = list()
nextPaths = list()
skipWord = -1
for wordNumb in range(len(wordArray)):
word = wordArray[wordNumb]
if wordNumb == skipWord:
continue
elif word == "from":
currentList.append(wordArray[wordNumb + 1])
skipWord = wordNumb + 2
elif word == "import":
currentList.append(wordArray[wordNumb + 1])
currentList = set(currentList)
for i in currentList:
print(i)
print("Found imports in '" + path + "'")
print("Finding paths for imports in '" + path + "':")
currentList2 = currentList.copy()
currentList = list()
for i in currentList2:
if i in dependenciesNames:
print(i, "already found")
else:
dependenciesNames.append(i)
try:
fileInfo = importlib.machinery.PathFinder().find_spec(i)
print(fileInfo.origin)
dependenciesPaths.append(fileInfo.origin)
currentList.append(fileInfo.origin)
except AttributeError as e:
print(e)
print(i)
print(importlib.machinery.PathFinder().find_spec(i))
# print(red, "Odd noneType import called ", i, " in path ", path, end, sep='')
print("Found paths for imports in '" + path + "'")
for fileInfo in currentList:
main(fileInfo)
except Exception as e:
print(e)
if __name__ == "__main__":
# args
args = sys.argv
print(args)
if len(args) == 2:
p = args[1]
elif len(args) == 3:
p = args[1]
open(args[2], "a").close()
sys.stdout = open(args[2], "w")
else:
print('Usage')
print('PyDependencies <InputFile>')
print('PyDependencies <InputFile> <OutputFile')
sys.exit(2)
if not os.path.exists(p):
print(red, "Path '" + p + "' is not a real path", end, sep='')
elif os.path.isdir(p):
print(red, "Path '" + p + "' is a directory, not a file", end, sep='')
elif "".join(pathlib.Path(p).suffixes) != ".py":
print(red, "Path '" + p + "' is not a python file", end, sep='')
else:
print(green, "Path '" + p + "' is a valid python file", end, sep='')
main(p)
deps = set(dependenciesNames)
print(deps)
sys.exit()