-
Notifications
You must be signed in to change notification settings - Fork 3
PythonVirtualEnvironments virtualenv
If you do anything with Python at all, you need to learn about virtual environments. The reason is that O/S's come with a Python installed. If it is not what you want, by far the easiest and cleanest solution is to create a virtual environment within which you can install just what you want. This gives you a self-contained Python environment and avoids messing with the system-wide Python.
The follow instructions were adapted from the JText Project at BYU. Thanks to Easquel Huang for originally creating them.
First - Install the package. Run the commands below:
# for Ubuntu system
# This first step will make 'python' run python3 instead of python (needed for 16.04 Ubuntu, for example)
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1
pip3 install virtualenv
pip3 install virtualenvwrapper
# for Mac system
sudo pip3 install virtualenv
sudo pip3 virtualenvwrapper
Second - Add the environment variable to the system path. Run the command below:
# for Ubuntu system
mkdir $HOME/.virtualenvs
vim ~/.bashrc
# for Mac system
mkdir ~/.virtualenvs
vim ~/.bash_profile
Add the following two lines of codes into the end of .bashrc(for Ubuntu) or .bash_profile(for Mac) file, then save it.
# for Ubuntu system
export WORKON_HOME=$HOME/.virtualenvs
source ~/.local/bin/virtualenvwrapper.sh
# for Mac system
export WORKON_HOME=~/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh
Third - Reload from .bashrc or .bash_profile. Run the command below:
# for Ubuntu
source ~/.bashrc
# for Mac
source ~/.bash_profile
Fourth - Testing - run the command below to test if your installation is right:
mkvirtualenv --help
If there are options and usages shown in the screen, congratulations you succeed.
Fifth - Create your own virtual environment. Run the command below (note that the name "Myvirenv_py3" is not special - you can choose any name you want to use):
mkvirtualenv -p python3 Myvirenv_py3
Run the command below to show the list of virtual environments you create.
# for Ubuntu
workon
# for Mac
lsvirtualenv -b
Sixth - Enter, exit and delete your own virtual environment.
Run the command workon Myvirenv_py3 to enter the "Myvirenv_py3" environment.
Run the command deactivate to exit the current virtual environment.
If you want to delete one specific virtual environment (for example the "Myvirenv_py3"), run the command rmvirtualenv Myvirenv_py3.
Last - Use your virtual environment.
Once your virtual environment is activated (you can tell by the new info prepended to the command prompt), anything you install using pip and the like will install ONLY into that virtual environment. When you exit the environment, it will all be invisible and your system will be like it originally was.
Initially created by Brent Nelson, April 2020.