Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Install a package and write to requirements.txt with pip

Tags:

python

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. For those familiar with npm, it's essentially what npm install --save does.

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.

So the following psuedocode:

$ pip install nose2 --save 

Would result in a requirements.txt file with:

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.

like image 477
Nick Tomlin Avatar asked Nov 15 '13 16:11

Nick Tomlin


People also ask

Does pip update requirements txt?

this will automatically upgrade all packages from requirements. txt (make sure to install pip-tools using pip install command). Pip-tools is working great -- updated syntax is pip-compile -U requirements. txt .


2 Answers

To get the version information, you can actually use pip freeze selectively after install. 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. Pip isn't case sensitive with package names, so you will probably want that.

like image 100
dusktreader Avatar answered Sep 23 '22 13:09

dusktreader


I've written the following bash function which I use;

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` 
like image 30
William Avatar answered Sep 25 '22 13:09

William