简体   繁体   English

安装包并使用pip写入requirements.txt

[英]Install a package and write to requirements.txt with pip

I'm searching for a way to install a package with pip, and write that package's version information to my project's requirements.txt file. 我正在寻找一种使用pip安装包的方法,并将该包的版本信息写入我的项目的requirements.txt文件。 For those familiar with npm , it's essentially what npm install --save does. 对于那些熟悉npm的人来说 ,它本质上就是npm install --save所做的。

Using pip freeze > requirements.txt works great, but I've found that I forget to run this, or I can accidentally include unused packages that I'd installed for testing but decided not to use. 使用pip freeze > requirements.txt工作得很好,但我发现我忘了运行它,或者我可能会意外地包含我为测试而安装但未决定使用的未使用的软件包。

So the following psuedocode: 所以下面的伪代码:

$ pip install nose2 --save

Would result in a requirements.txt file with: 会导致一个requirements.txt文件:

nose2==0.4.7

I guess I could munge the output of save to grab the version numbers, but I am hoping there is an easier way. 我想我可以使用save的输出来获取版本号,但我希望有一种更简单的方法。

To get the version information, you can actually use pip freeze selectively after install. 要获取版本信息,您可以在安装后有选择地使用pip冻结。 Here is a function that should do what you are asking for: 这是一个应该满足您要求的功能:

pip_install_save() {
    package_name=$1
    requirements_file=$2
    if [[ -z $requirements_file ]]
    then
        requirements_file='./requirements.txt'
    fi
    pip install $package_name && pip freeze | grep -i $package_name >> $requirements_file
}

Note the -i to the grep command. 请注意grep命令的-i。 Pip isn't case sensitive with package names, so you will probably want that. Pip与包名称不区分大小写,因此您可能需要它。

Just add smth like 只需添加smth就好

function pips() {
    echo $'\n'$1 >> requirements.txt; pip install $1
}

into your .bashrc or .bash_profile and use pips command to install package and save it's name into requirements.txt example: 到.bashrc或.bash_profile并使用pips命令安装包并将其名称保存到requirements.txt示例:

pips django-waffle

based on Akash Kothawale comment :) 基于Akash Kothawale评论:)

I've written the following bash function which I use; 我编写了以下使用的bash函数;

function pip-save() {
    for pkg in $@; do
        pip install "$pkg" && {
            name="$(pip show "$pkg" | grep Name: | awk '{print $2}')";
            version="$(pip show "$pkg" | grep Version: | awk '{print $2}')";
            echo "${name}==${version}" >> requirements.txt;
        }
    done
}

This saves the canonical package name to requirements, as well as the version installed. 这会将规范包名称保存到需求以及安装的版本。 Example usage; 用法示例;

$ pip-save channels asgi_redis
# will save the following to requirements.txt (as of writing):
# ---
# channels==1.0.1
# asgi-redis==1.0.0
# ---
# note how asgi_redis is translated to its canonical name `asgi-redis`

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

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