JeffGallant
JeffGallant

Reputation: 449

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.

Upvotes: 9

Views: 14887

Answers (2)

Train
Train

Reputation: 575

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.

Upvotes: 3

wim
wim

Reputation: 362478

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

Upvotes: 16

Related Questions