Sublime Text3 and Virtualenvs

Sublime text3 and virtualenvs

Hopefully this is along the lines you are imagining. I attempted to simplify my solution and remove some things you likely do not need.

The advantages of this method are:

  • Single button press to launch a SublimeREPL with correct interpreter and run a file in it if desired.
  • After setting the interpreter, no changes or extra steps are necessary when switching between projects.
  • Can be easily extended to automatically pick up project specific environment variables, desired working directories, run tests, open a Django shell, etc.

Let me know if you have any questions, or if I totally missed the mark on what you're looking to do.

Set Project's Python Interpreter

  1. Open our project file for editing:

     Project -> Edit Project
  2. Add a new key to the project's settings that points to the desired virtualenv:

     "settings": {
    "python_interpreter": "/home/user/.virtualenvs/example/bin/python"
    }

A "python_interpreter" project settings key is also used by plugins like Anaconda.

Create plugin to grab this setting and launch a SublimeREPL

  1. Browse to Sublime Text's Packages directory:

    Preferences -> Browse Packages...
  2. Create a new python file for our plugin, something like: project_venv_repls.py

  3. Copy the following python code into this new file:

    import sublime_plugin

    class ProjectVenvReplCommand(sublime_plugin.TextCommand):
    """
    Starts a SublimeREPL, attempting to use project's specified
    python interpreter.
    """

    def run(self, edit, open_file='$file'):
    """Called on project_venv_repl command"""
    cmd_list = [self.get_project_interpreter(), '-i', '-u']

    if open_file:
    cmd_list.append(open_file)

    self.repl_open(cmd_list=cmd_list)

    def get_project_interpreter(self):
    """Return the project's specified python interpreter, if any"""
    settings = self.view.settings()
    return settings.get('python_interpreter', '/usr/bin/python')

    def repl_open(self, cmd_list):
    """Open a SublimeREPL using provided commands"""
    self.view.window().run_command(
    'repl_open', {
    'encoding': 'utf8',
    'type': 'subprocess',
    'cmd': cmd_list,
    'cwd': '$file_path',
    'syntax': 'Packages/Python/Python.tmLanguage'
    }
    )

Set Hotkeys

  1. Open user keybind file:

     Preferences -> Key Bindings - User
  2. Add a few keybinds to make use of the plugin. Some examples:

    // Runs currently open file in repl
{
"keys": ["f5"],
"command": "project_venv_repl"
},
// Runs repl without any file
{
"keys": ["f6"],
"command": "project_venv_repl",
"args": {
"open_file": null
}
},
// Runs a specific file in repl, change main.py to desired file
{
"keys": ["f7"],
"command": "project_venv_repl",
"args": {
"open_file": "/home/user/example/main.py"
}
}

How to use SublimeText within a venv?

Virtual Environment is an independent and isolated installation of the python interpreter into which you have installed flask. Your sublime text is still probably running your original python interpreter(not the virtual env one). So you need to tell sublime which interpreter you want to use. It is probably best to learn about build systems if you want to make this process of switching between different environments quick and painless.


I tried to manually edit the python build but it was not successful and it would be a pain to manually change it every time you wanted to swtich to a new python env. So we go with build systems.



  1. Select Tools >> New build system in sublime text. This will open a new build system config file. In that file delete everything and paste this:
{
"cmd": ["PATH TO YOUR DESIRED PYTHON INTERPRETER","-u", "$file"],
"selector": "source.python",
"file_regex": "^\\s*File \"(...*?)\", line ([0-9]*)"
}

To work out the path to the desired python interpreter, in the terminal, go to your project directory, make sure it is activated, then use which python3 command.


  1. Save the file and then run your program with the new build system. It will appear in the build system tab in tools.

I would highly reccomend watching this video which does a good job of explaining the whole concept.

Virtualenvs in Sublime Text 4

There is a package Virtualenv for ST3, you can downgrade. Currently it doesn't work with ST4 (issue).
You can specify build system per project:

  • Create sublime project or add existing directory to sublime project
  • Goto Project -> Edit Project
  • Add this and save in root of you project:
{
"build_systems":
[
{
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", # highlight line on error
"name": "<proj-name>",
"selector": "source.python",
"shell_cmd": "/path/to/virtualenv/.venv/bin/python -u \"$file\""
},
],
"folders":
[
{
"path": "."
},
],

}
  • If you don't want to store .sublime-project files in project's root dir, specify full path to project's root dir in: "path": "/path/to/proj"
  • Still, you need to chose build system before running scripts. In this case it'll be <proj-name>
  • You can generate this config programmatically.

More options for Project config here.

If you find something flexible for venvs, hit me up)

Using virtualenv with Sublime Text 3 and SublimeREPL

The ST3 build system and the SublimeREPL provide two different pieces of functionality. The build system is something you would typically use when working with a compiled language like C. It allows you to define how you want to build your program from the source files.

You can also use the build system with Python. In this case, it would compile for you the file which is currently open.

The SublimeREPL on the other hand, allows you to run a terminal session inside Sublime and also (among other things) evaluate the files within the context of that session. I would suggest you take a look at the documentation for SublimeREPL and Python:

Both stock Python and Execnet integrations support virtualenv. Various ways to work with Python, including PDB and IPython, are supported.

For virtualenv created environments to be discoverable by SublimeREPL they should be created or symlinked in one of the following:

  • ~/.virtualenvs default for virtualenvwrapper
  • ~/.venvs default for venv

Alternatively, more paths can be added to “python_virtualenv_paths” in the SublimeREPL configuration file.

How do I use Virtual Environments with SublimeREPL?

It is mentioned in the docs:

For virtualenv created environments to be discoverable by SublimeREPL
they should be created or symlinked in one of the following:

  • ~/.virtualenvs default for virtualenvwrapper
  • ~/.venvs default for venv

Alternatively, more paths can be added to “python_virtualenv_paths” in
the SublimeREPL configuration file.

If your virtualenvs are created in another directory add them to SublimeREPL.sublime-settings. For me, they are in ~/Envs:

{
"python_virtualenv_paths": ["C:\\Users\\my_username\\Envs"]
}

Assuming you're using the correct path, sublimeREPL: Python - virtualenv allows you to select the venv you want to work with:

Use Sublime with virtualenv

Ah. The "cmd" should point to the python folder within the virtualenv:

"cmd" : ["/Users/thumbtackthief/.virtualenvs/chorus/bin/python", "$file"]

Yay.

How can I use editors/IDEs with a virtual environment | python and venv?

If you can make your tools use the python binary placed within the directory of your virtual environment, then you should be all set (no need to activate and desactivate the virtual environment). The full path should be something like:

  • /path/to/venv/bin/python
  • C:\path\to\venv\Scripts\python.exe

If everything is setup right the other Python executable scripts (such as pip, pylint, pep8, and so on) are also located in that same directory and can be used directly without activating the virtual environment. But as always I'd recommend using the executable modules instead of the scripts whenever possible (/path/to/venv/bin/python -m pip somecommand instead of /path/to/venv/bin/pip somecommand).

References:

  • https://docs.python.org/3/library/venv.html#creating-virtual-environments
  • https://snarky.ca/why-you-should-use-python-m-pip/


Related Topics



Leave a reply



Submit