Search code examples
pythonpython-venvvirtual-environment

How can I change the Python interpreter in virtual environment (Ubuntu 18.04LTS)?


I always used Anaconda on Windows so far and could set up an environment while choosing which exact Python to use. E.g. conda create -n myEnvName python=3.7

Now, I want to familiarize with Ubuntu 18.04 LTS and use basic Python environments.

So I followed these steps:

  1. Created folder in my home = ~/.venvPython
    • (a) I think I already had a 2.7 and 3.6 by default on the OS.
    • (b) I do not remember for sure, I think I had to do this sudo apt-get install python3-venv.
  2. Created environment this way after CD'ing to .venvPython folder ran this: python3 -m venv venv1BigDataPgm2
  3. source ~/.venvPython/venv1BigDataPgm2/bin/activate
  4. Command python --version says: Python 3.6.9

Running whereis Python shows this:

rohit@rohitUb18043LTS:~$ whereis python
python: /usr/bin/python3.6 /usr/bin/python3.6-config /usr/bin/python2.7-config /usr/bin/python3.6m-config /usr/bin/python /usr/bin/python3.6m /usr/bin/python2.7 /usr/lib/python3.8 /usr/lib/python3.7 /usr/lib/python3.6 /usr/lib/python2.7 /etc/python3.6 /etc/python /etc/python2.7 /usr/local/lib/python3.6 /usr/local/lib/python2.7 /usr/include/python3.6 /usr/include/python3.6m /usr/include/python2.7 /usr/share/python /usr/share/man/man1/python.1.gz

My doubts: Can I specify a Python version directly while creating the environment like with conda? How do I change this to some other interpreter instead of the 3.6.9? Do I have to manually install a different Python first, then point it somehow?

Please guide me. Thank you. Rohit


Solution

  • As far as I can tell the venv standard library appeared in Python 3.3 and was never backported to 2.7.

    venv can only create virtual environment for its own version of the interpreter and the virtual environment directory can not be moved to a different location or be renamed. Python 3.foo can not create a virtual environment for Python 3.bar. So it is best to pick the wanted interpreter right from the start.

    Since, as shown by the output of whereis python, you seem to already have multiple Python interpreters already installed, you should be able to do something like the following:

    $ /path/to/python3.3 -m venv /path/to/my/venvs/venv33
    $ /path/to/python3.8 -m venv /path/to/my/venvs/venv38
    

    There seems to be a way to change the Python interpreter associated with a virtual environment (I have not tested it, not sure what the limitations are):

    $ /path/to/python3.8 -m venv --upgrade /path/to/my/venvs/venv33
    

    Alternatively use virtualenv which seems to offer a bit more flexibility, but is probably less efficient (its next major release, virtualenv 20, should bring a lot of improvements though).