Using Python Virtual Environments with Sublime Text
When developing in Python I enjoy using Sublime Text, especially its ability to run/build right from Sublime by simply pressing COMMAND+B. Meaning that I dont have to go out of the editor to the terminal to run the Python program.
Sample Python Program:
#!/usr/bin/env python
print "Hello World"
In sublime, I can program, run the program and see the result, increasing my productivity:
But what if I want to run a Python Virtual Environment and its benefits (see developing-in-python-using-python-virtual-environments). Once the virtual environment is activated your terminal will use the Python Virtual Environment just fine, but Sublime Text will not, it will continue to use the system-wide Python environment by default.
Example: Having a Python module (e.g. IPy) installed in your virtual environment, but not system-wide, and having the Python virtual environment active:
# Python code:
#!/usr/bin/env python
import IPy
print "Hello World"
# Running from terminal - (OK):
$ python hello.py
Hello World
# Running from Sublime - (NOT OK):
To make Sublime Text use the virtual environment you need to create a Sublime project and edit its properties to use the Virtual Env.
# Create Sublime Project Go to Project -> Save Project As… // I named mine blog.sublime-project
# Edit project properties by editing the file in sublime to be as follows: Note: Remember the name: label as this is how you will use the build with… option The shell_cmd: label is the command that will run when you build. It is far from perfect as you have to hardcode the Python program in the configuration, but at least works.
{
"folders":
[
{
"path": "."
}
],
"virtualenv": "env",
"build_systems": [
{
"name": "PYTHON_VENV",
"shell_cmd": "env/bin/python hello.py"
}
]
}
# Prepare Sublime to use your new build system: Tools -> Build Systems -> PYTHON_VENV
# Now you can now continue to code and use COMMAND+B to build/run your programs without leaving your Sublime Text editor: