自动创建requirements.txt

问题:自动创建requirements.txt

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

Sometimes I download the python source code from github and don’t know how to install all the dependencies. If there is no requirements.txt file I have to create it by hands. The question is: Given the python source code directory is it possible to create requirements.txt automatically from the import section?


回答 0

如果您使用虚拟环境,pip freeze > requirements.txt就可以了。IF NOTpigar将是您不错的选择。

顺便说一句,我不保证它能在2.6下使用。

更新

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

对于Python 3,请在下面使用

pip3 freeze > requirements.txt

If you use virtual environment, pip freeze > requirements.txt just fine. IF NOT, pigar will be a good choice for you.

By the way, I do not ensure it will work with 2.6.

UPDATE:

Pipenv or other tools is recommended for improving your development flow.

For Python 3 use below

pip3 freeze > requirements.txt

回答 1

您可以使用以下代码来生成requirements.txt文件:

pip install pipreqs

pipreqs /path/to/project

与pipreqs相关的更多信息可以在这里找到。

有时您会碰到pip freeze,但这会保存环境中的所有程序包,包括您当前项目中未使用的程序包。

You can use the following code to generate a requirements.txt file:

pip install pipreqs

pipreqs /path/to/project

more info related to pipreqs can be found here.

Sometimes you come across pip freeze, but this saves all packages in the environment including those that you don’t use in your current project.


回答 2

就我而言,我使用的是Anaconda,因此从我的环境中的conda终端运行以下命令即可解决该问题,并自动为我创建了此需求txt文件:

conda list -e > requirements.txt

摘自Github链接pratos / condaenv.txt

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

conda env export > <environment-name>.yml

供其他人使用的环境…或者如果要在其他计算机上创建新环境:conda env create -f .yml

.yml选项在这里找到

In my case, I use Anaconda, so running the following command from conda terminal inside my environment solved it, and created this requirements txt file for me automatically:

conda list -e > requirements.txt

This was taken from this Github link pratos/condaenv.txt

If an error been seen, and you are using anaconda, try to use the .yml option:

conda env export > <environment-name>.yml

For other person to use the environment…Or if you are creating a new enviroment on other machine: conda env create -f .yml

.yml option been found here


回答 3

确保为python3.7运行pip3。

pip3 freeze >> yourfile.txt

在执行上述命令之前,请确保已创建虚拟环境。

python3:

pip3 install virtualenv
python3 -m venv <myenvname> 

python2

pip install virtualenv
virtualenv <myenvname>

之后,将您的源代码放在目录中。如果您现在运行python文件,则可能在使用非本机模块时无法启动。您可以安装那些正在运行的模块

pip3 install <module> or pip install <module> 

除了您所在的环境,这不会影响您的整个模块列表。

现在,您可以在顶部执行命令,现在有了一个需求文件,其中仅包含您在虚拟环境中安装的模块。现在,您可以在顶部运行命令。

我建议大家使用环境,因为这样的事情会使事情变得容易。

希望这会有所帮助。

Make sure to run pip3 for python3.7.

pip3 freeze >> yourfile.txt

Before executing the above command make sure you have created a virtual environment.

python3:

pip3 install virtualenv
python3 -m venv <myenvname> 

python2:

pip install virtualenv
virtualenv <myenvname>

After that put your source code in the directory. If you run the python file now, probably It won’t launch If you are using non-native modules. You can install those modules runing

pip3 install <module> or pip install <module> 

This will not affect you entire module list except the environment you are In.

Now you can execute the command at the top and now you have a requirements file which contains only the modules you installed in the virtual environment. Now you can run the command at the top.

I advise everyone to use environments as It makes things easier when It comes to stuff like this.

Hope this helped.


回答 4

如果与我面临同样的问题,即不在虚拟环境上,并且想要特定项目或从所选文件夹(包括子文件夹)和pipreqs获得requirements.txt,则不支持。

您可以使用 :

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))

PS:在检查Fuzzylogic时,可能还有一些其他库。

If Facing the same issue as mine i.e. not on the virtual environment and wants requirements.txt for a specific project or from the selected folder(includes children) and pipreqs is not supporting.

You can use :

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))

P.S: It may have a few additional libraries as it checks on fuzzylogic.


回答 5

Python 3的最佳方法是:

pip3 freeze > requirements.txt

对我有用

best way for Python 3 is:

pip3 freeze > requirements.txt

it worked for me…


回答 6

如果您使用的是PyCharm,则在您将项目打开或克隆到PyCharm时,它会显示警报,并要求您安装所有必需的软件包。

if you are using PyCharm, when you open or clone the project into the PyCharm it shows an alert and ask you for installing all necessary packages.