有时我从github下载python源代码,不知道如何安装所有的依赖项。如果没有requirements.txt文件,我必须手工创建它。 问题是: 给定python源代码目录,是否有可能从导入部分自动创建requirements.txt ?


当前回答

Python 3的最佳方式是:

pip3 freeze > requirements.txt

这对我很管用……

其他回答

我盲目地遵循公认的使用答案 Pip3冻结> requirements.txt

它生成了一个巨大的文件,其中列出了整个解决方案的所有依赖项,这不是我想要的。

因此,您需要弄清楚您试图生成什么样的requirements.txt。

如果您需要一个包含所有依赖项的requirements.txt文件,那么可以使用pip3

pip3 freeze > requirements.txt

但是,如果您想生成一个最小的requirements.txt,它只列出您需要的依赖项,那么可以使用pipreqs包。如果您在项目中的每个组件级别都有大量的requirements.txt文件,而在解决方案范围级别上没有一个文件,那么这将特别有用。

pip install pipreqs
pipreqs [path to folder]
e.g. pipreqs .
     pipreqs . --force --ignore=tests (Overwrites exisiting requirements.txt, ignores the tests directory)

建议使用Pipenv或其他工具来改进开发流程。

pip3 freeze > requirements.txt  # Python3
pip freeze > requirements.txt  # Python2

如果您不使用虚拟环境,pigar将是一个很好的选择。

如果遇到和我一样的问题,即不在虚拟环境中,并且想要特定项目的requirements.txt或从选定的文件夹(包括子)和pipreqs是不支持的。

你可以使用:

import os
import sys
from fuzzywuzzy import fuzz
import subprocess

path = "C:/Users/Username/Desktop/DjangoProjects/restAPItest"


files = os.listdir(path)
pyfiles = []
for root, dirs, files in os.walk(path):
      for file in files:
        if file.endswith('.py'):
              pyfiles.append(os.path.join(root, file))

stopWords = ['from', 'import',',','.']

importables = []

for file in pyfiles:
    with open(file) as f:
        content = f.readlines()

        for line in content:
            if "import" in line:
                for sw in stopWords:
                    line = ' '.join(line.split(sw))

                importables.append(line.strip().split(' ')[0])

importables = set(importables)

subprocess.call(f"pip freeze > {path}/requirements.txt", shell=True)

with open(path+'/requirements.txt') as req:
    modules = req.readlines()
    modules = {m.split('=')[0].lower() : m for m in modules}


notList = [''.join(i.split('_')) for i in sys.builtin_module_names]+['os']

new_requirements = []
for req_module in importables:
    try :
        new_requirements.append(modules[req_module])

    except KeyError:
        for k,v in modules.items():
            if len(req_module)>1 and req_module not in notList:
                if fuzz.partial_ratio(req_module,k) > 90:
                    new_requirements.append(modules[k])

new_requirements = [i for i in set(new_requirements)]

new_requirements

with open(path+'/requirements.txt','w') as req:
    req.write(''.join(new_requirements))

附注:它可能有一些额外的库,因为它检查模糊逻辑。

@Francis说得对- https://stackoverflow.com/a/65728461/1021819

但我要补充一点:

对Jupyter笔记本的额外支持-即.ipynb文件-您现在可以使用https://pypi.org/project/pipreqsnb(与pipreqs相同的语法):

pip install pipreqsnb
pipreqsnb .

[我不是作家]

在我的例子中,我使用Anaconda,所以在我的环境中从conda终端运行以下命令解决了这个问题,并自动为我创建了这个requirements.txt文件:

conda list -e > requirements.txt

这是从这个Github链接pratos/condaenv.txt

如果看到错误,并且您正在使用anaconda,请尝试使用.yml选项:

conda env export > <environment-name>.yml

供其他人使用该环境,或者如果您正在另一台机器上创建新环境:

conda env create -f <environment-name>.yml

.yml选项在这里找到