How to Run PIP Command with Specific Python Version

This question has been answered online in multiple places. I want to highlight few challenges faced while running pip command with multiple versions of Python installed in the operating system & my preferred way of doing it.
I have an old machine with Ubuntu 16.04. By default Ubuntu 16 has Python 2.7 and Python 3.5. So we can run Python 2.7 interpreter & Python 3.5 interpreter with python & python3 commands respectively.

To use pip for Python 2.7, we can use below command:

pip install <pkg-name>

If we want to install some package for Python3 environment using pip, we can use command as below:

pip3 install <pkg-name>

This is one way to run pip with Python2 & Python3 separately from the same machine.

Now let’s increase the complexity a bit. For an example, I needed to install Python 2.7.10 for running Cassandra in my Ubuntu box. Ubuntu 16 uses Python 2.7.12 version as default. So now I have two different Python2 versions.

To run Python 2.7.12 interpreter, we can simply run below command:

python <>

To run Python 2.7.10 interpreter, we can run below command:

python2.7 <> 

To run Python 3.5 interpreter, we can use below command:

python3 <>

But how do we run pip then? If we run pip install as above, which Python 2.7 would execute it? It will be executed by default Ubuntu Python (v. 2.7.12).
To solve this, we can use python -m command. -m option basically loads the python module and runs it as a script. So we can mention the correct python interpreter, load & run pip using this command.

For Python version 2.7.12 (default Python2 in Ubuntu 16.04):

python -m pip install <pkg-name>

For Python version 2.7.10:

python2.7 -m pip install <pkg-name>

For Python version 3.5 (default Python3 in Ubuntu 16.04):

python3 -m pip install <pkg-name>

This is the preferred way for me because I can run pip for any version of Python that I installed.

Leave a Comment