Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get virtualenv to run Python 3 instead of Python 2.7?

On Mac, if I simply open a new terminal window and run:

python --version

I get:

3.6

but if I do this:

 virtualenv venv && source venv/bin/activate

and then, in that environment, I run :

python --version

I get:

2.7

I need virtualenv to run 3.6. How do I do that?

This :

/usr/bin/python

is 2.7 but this:

/usr/local/bin/python 

is 3.6. The path for my normal user has /usr/local/bin come up before /usr/bin/. Is virtualenv running as someone else? How do I control its path?

I ran this:

virtualenv -p /usr/local//Cellar/python/3.6.5/bin/python3 venv

but then I do this:

virtualenv venv && source venv/bin/activate

and I'm running in an environment with 2.7.

like image 679
JeffGallant Avatar asked May 08 '18 18:05

JeffGallant


People also ask

Does Python 2.7 support virtualenv?

Python and OS Compatibility. virtualenv works with the following Python interpreter implementations: CPython versions 2.7, 3.5, 3.6, 3.7, 3.8, 3.9, 3.10.

How do I use Python 3.7 in venv?

Show activity on this post. You will see something like this: Running virtualenv with interpreter C:\Python37\python.exe Using base prefix 'C:\Python37' New python executable in C:\Users\XXXX\Documents\GitHub\MyProject\venv\Scripts\python.exe Installing setuptools, pip, wheel... done.


2 Answers

On Python 3 you don't need virtualenv script anymore, you should just use the venv module included with standard lib:

python3 -m venv myvenv

But if you really want to keep using the old virtualenv script, you can - specify the interpreter explicitly with the -p option:

virtualenv -p /path/to/python3 myvenv
like image 75
wim Avatar answered Oct 16 '22 12:10

wim


The easiest way is to change python globally to Python3 as I think you're using it more often than Python 2.7 (or hopefully always). To achieve this, add the following line of code at the end of your .bash_profile:

alias python='python3'

virtuanenv is using /usr/bin/python, hence it should work now.

If you don't want to change it globally, than you should use the following command to create your Python3.6 virtual environment:

python3 -m venv venv

or the explicit Python version if you have multiple Python3 versions installed:

python3.6 -m venv venv

On more suggestion at the end: I recommend you to read something about pipenv as it's the new recommended way to handle virtual environments and your whole package management at once. It's super easy and fixes a lot of common issues. Here's a nice article from realpython.com on that topic.

Hope I could help you. Have a nice day.

like image 24
Train Avatar answered Oct 16 '22 13:10

Train