Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inside virtual env, "sudo pip" links to the global python pip

Working inside a vagrant environment, inside a python virtual environment, when I try to install a python package using

(venv) vagrant@vagrant-ubuntu-trusty-64:~$ pip install <package_name>

I receive a permission error:

error: could not create '/home/vagrant/venv/lib/python2.7/site-packages/<package_name>': Permission denied

When I use sudo to install:

(venv) vagrant@vagrant-ubuntu-trusty-64:~$ sudo pip install <package_name>

the install is successful, but the package is not installed inside venv, but instead inside the global python directory.

I can successfully install the package inside venv by using sudo and specifying the path to pip:

(venv) vagrant@vagrant-ubuntu-trusty-64:~$ sudo /home/vagrant/venv/bin/pip install <package_name>

This is quite convoluted though. So how can I stop sudo pip linking to the global python pip?

Thank you

like image 343
Thomas Hopkins Avatar asked Jan 02 '17 16:01

Thomas Hopkins


2 Answers

I had the same problem with pip vs sudo pip and virtualenv pip vs local pip. I was logged in as root user when I created my venv months ago. So when I wanted to install a new pip package got permission denied. So tried the same command with sudo, but then it installed the package on my local pip.

Lesson learned. I should not use sudo inside a venv.

Fixed it with:

chmod -R 0777 venv_folder_path_here

-R switch for recursive change in venv folder.

And then activate your venv and try pip install:

/home/username_here/venv/project_name_here/bin/activate
(venv_name) pip install package_name_here
like image 97
jturi Avatar answered Oct 12 '22 11:10

jturi


The root problem is that sudo does not by default inherit the user's environment as it executes the command. This is what you want - trust me on this.

In your case, your pip is either guided to the venv that it can't write to or - under sudo - to root's environment where you don't want it to be.

The solution you posted is actually valid: If you use sudo, be sure to tell it exactly what to do, how to do it and whom to do it to! All of the aforementioned can be controlled by the user's environment variables so caution is key.

You may also use sudo -E, which does inherit the calling user's environment and should therefore preserve your venv. Be sure to read sudo's man-page or do some googling about all the possible trouble you could get in, though.

like image 28
user2722968 Avatar answered Oct 12 '22 09:10

user2722968