Virtualenv is a tool used to create an isolated Python environment. This environment has its own installation directories that doesn't share libraries with other virtualenv environments (and optionally doesn't access the globally installed libraries either).
Virtualenv is the easiest and recommended way to configure a custom Python environment.
To run the commands in this article, you must log into your server via SSH with your Shell user. View the following articles for more information:
This article uses Python version 2.7. If you want to set up virtualenv using Python 3, view the following article instead:
Virtualenv is installed by default on all DreamHost servers. But, if for some reason you need to install it, you would run the following command in your user's directory:
[server]$ pip install virtualenv
Creating a virtual environment using a custom Python version
When working with virtual environments in Python, it's common to use a custom version of Python rather than the server's version. View the following article to install any version of Python you like.
To create a new virtual environment using this custom Python version, follow these steps:
- Make a note of the full file path to the custom version of Python you just installed. If you've followed the instructions in the installation article, the full path is:
- Navigate to your site's directory. This is where you'll create the new virtual environment:
[server]$ cd $HOME/example.com
- Create the virtual environment at the same time you specify the version of Python you wish to use. In this example, the project is titled 'my_project'.
[server]$ virtualenv -p /home/username/opt/python-2.7.7/bin/python my_project
If you leave out the path to a specific version of Python, the system version will be used instead.
- This creates a local copy of your environment specific to this website. While working on this website, you should activate the local environment in order to make sure you're working with the right versions of your tools and packages.
- Run the following to activate this new virtual environment:
[server]$ source my_project/bin/activate
- Finally, check the version of Python being used:
[server]$ python -V Python 2.7.7
From now on, any package that you install using pip is placed in the virtual environments project folder, isolated from the global Python installation.
Deactivating your virtualenv
If you are finished working in the virtual environment for the moment, you can deactivate it by running the following:
- This puts you back into your Shell user's default settings.
Deleting your virtual environment
To delete a virtual environment, just delete project folder. In this case, it would be:
[server]$ rm -rf /home/username/example.com/my_project
Installing custom modules
View the following article for information on how to use pip to install Python modules.