Tuesday, February 1, 2022

[SOLVED] Creating a virtualenv with python 2

Issue

In ubuntu 16.04 I have in bashrc:

alias python=python3.6

In other words, the command python starts python 3.6.

Now I want a virtualenv with python 2.7.

I have installed virtualenv:

virtualenv -p python2 pgadmin4

Then activated it.

Now check:

$ which python
/home/michael/PycharmProjects/venv/pgadmin4/bin/python

Doublecheck:

(pgadmin4) michael@michael-desktop:~/PycharmProjects/venv/pgadmin4/bin$ ls -la
    total 3516
    drwxrwxr-x 2 michael michael    4096 окт 12 13:05 .
    drwxrwxr-x 7 michael michael    4096 окт 12 13:05 ..
    -rw-rw-r-- 1 michael michael    2102 окт 12 13:05 activate
    -rw-rw-r-- 1 michael michael    1044 окт 12 13:05 activate.csh
    -rw-rw-r-- 1 michael michael    2242 окт 12 13:05 activate.fish
    -rw-rw-r-- 1 michael michael    1137 окт 12 13:05 activate_this.py
    -rwxrwxr-x 1 michael michael     272 окт 12 13:05 easy_install
    -rwxrwxr-x 1 michael michael     272 окт 12 13:05 easy_install-2.7
    -rwxrwxr-x 1 michael michael     244 окт 12 13:05 pip
    -rwxrwxr-x 1 michael michael     244 окт 12 13:05 pip2
    -rwxrwxr-x 1 michael michael     244 окт 12 13:05 pip2.7
    lrwxrwxrwx 1 michael michael       7 окт 12 13:05 python -> python2
    -rwxrwxr-x 1 michael michael 3546104 окт 12 13:05 python2
    lrwxrwxrwx 1 michael michael       7 окт 12 13:05 python2.7 -> python2
    -rwxrwxr-x 1 michael michael    2361 окт 12 13:05 python-config
    -rwxrwxr-x 1 michael michael     251 окт 12 13:05 wheel

Well, just writing python must run python2.

But:

$ python
Python 3.6.2 (default, Jul 20 2017, 08:43:29) 

Could you give me a kick here?


Solution

When you activate a virtualenv, under the hood, the PATH environment variable is rewritten to give more priority to the bin directory of your virtualenv.

The which python command tells you the path you expect because it ignores any alias eventually configured. It looks at the PATH environment variable and tries to resolve the current python path.

Bash, instead, takes into account all the alias configured and when you types python, bash resolves the command to python3.6 which is not in you virtualenv bin directory and goes to the system one.

The only possible solutions are:

  1. remove the alias
  2. add a symlink python3.6 -> python inside the bin folder of your virtualenv


Answered By - Yusef Maali
Answer Checked By - Robin (WPSolving Admin)