51

I have different virtualenv's (made with virtualenwrapper) and I'd like to be able to specify which virtualenv to use with each project.

Since I'm using the SublimeREPL plugin for custom builds, how can I specify which python installation to build my project with?

For example, when I work on project A I want to run scripts with venvA's python, and when I work on project B I want to run things with venvB (using a different build script).

Rob Bednark
  • 25,981
  • 23
  • 80
  • 125
Doc
  • 5,078
  • 6
  • 52
  • 88
  • Can you specify what you mean by "using SublimeREPL plugin to have custom builds"? There is a method I use to automatically open and run python scripts with the project's virtualenv (in a SublimeREPL) with the push of a button. I'm unsure if this is exactly what you're looking for, though. – SoylentFuchsia Jul 28 '14 at 14:06
  • how do you set a project to run within a specific virtualenv? – Doc Jul 28 '14 at 15:06
  • 1
    There's no built-in way that I'm aware of. My method involves setting a project-level setting for "python_interpreter", then using a small custom plugin to pick up on that and run a sublimeREPL with it. If you like, I can go into more detail with a full answer when I have some time later. – SoylentFuchsia Jul 28 '14 at 15:15
  • yes please, it'll be very useful :) – Doc Jul 28 '14 at 15:18

5 Answers5

65

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"
        }
    }
MattDMo
  • 100,794
  • 21
  • 241
  • 231
SoylentFuchsia
  • 1,181
  • 9
  • 8
  • great post and great answer, but i can't make it works... i've installed flask in my venv just for try your scripts, but i can't make the .sublime-project settings read by sublime: it seems to ignore it :( – Doc Jul 29 '14 at 17:12
  • nvm, found the problem, i'm an idiot... thanks for your time! – Doc Jul 29 '14 at 17:23
  • Is it possible to get this into a new build system? I would like to select this build system with ctrl+shift+b... – maggie Jan 13 '16 at 06:24
  • I'd add the line " 'external_id': 'python' " to project_venv_repls - This allows keyboard shortcut transfer to repl and code evaluation. Otherwise it's spot on! – Piotr Sokol Apr 26 '16 at 14:39
  • @Soytoise You are not saying what should we select from the packages in the step: "Browse to Sublime Text's Packages directory: Preferences -> Browse Packages..." – elena Mar 22 '17 at 20:44
  • This is great! I used the Chain of Command plugin to save the file before running `project_venv_repl`. (https://packagecontrol.io/packages/Chain%20of%20Command) – Chris Chudzicki Aug 20 '17 at 20:41
  • Great post! @Soytoise I had to add `"extend_env": {"PYTHONIOENCODING": "utf-8"}` to `'repl_open', {...` in the last function to get proper output of unicode characters in the REPL. – absurd Aug 24 '17 at 09:11
  • @Soytoise How do set up the plugin to be able to send a line/selection/etc. to a REPL that is _already open_ (i.e. opened by pressing f5)? I tried different things but could not make it work. – absurd Aug 24 '17 at 09:17
  • This works, but how does Sublime know what the command `project_venv_repl` is supposed to do? – ZaxR Mar 30 '18 at 04:40
23

There is a sublime text3 package, named Virtualenv, allowing you to build using the Python from your virtualenv.

It supports any versions of Python in your virtualenv, and works very well for me (MacOS).

To install it, we just command+Shift+P to call out pacakge control (install it if you don't have it yet), then type install. Next type virtualenv, when you see it appears click return to install it.

After installing it, select Tools --> Build System --> Python + Virtualenv. Then you can use command + B to execute your Python projects.

Click Here to check further information.

Jay Wang
  • 2,650
  • 4
  • 25
  • 51
  • where do I add the path to my environment ? ex: ~/tensorflow/bin/activate – 39fredy Nov 13 '17 at 03:50
  • 3
    There is the call "VirtualEnv: Add Directory" – user1767754 Nov 23 '17 at 00:14
  • 1
    Open Menu Tools, Command Pallete (command+Shift+P) then Choose "VirtualEnv: Add Directory", fill out the path of your VirtualEnv under. Don´t forget to Activate using "VirtualEnv: Activate" – Anderson Tenorio Tagata May 09 '18 at 20:00
  • 1
    in addition to @user1767754 - "VirtualEnv: Add New" from command palette helped me. – alex1704 Jun 16 '18 at 20:10
  • I added local virtualenv directory (named `sites/path/venv3`), I trried to modify user settings adding also `"executable": "python -m venv3",` `""extra_paths": ["user/sites/path/venv3/bin/python3"]` but still have error `python: realpath couldn't resolve "/Library/Frameworks/Python.framework/Versions/3.6/bin/python"` - Could you please help @Jay Wong – user305883 Nov 04 '18 at 09:09
11

I have an alternative. Just creating a new 'Build System' which runs as if in the virtual environment. Here we call it 'my_python'. The aim is to use this build system to run my script directly without leaving sublime. You need to:

  1. First, preferences->Browse Packages. This will open a folder under which lies setting files. Go inside dir User and create a new file named my_python.sublime-build (composed of the build system name followed by .sublime_build. After doing this, go to Tools -> Build System and you will see a new option my_python.
  2. Add the following JSON settings to that file.

    {
        "shell_cmd": "/Users/Ted/bsd/vector/.v_venv/bin/python -u \"$file\"",
        "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
        "selector": "source.python"
    }
    

    Inside shell_cmd, change /Users/Ted/bsd/vector/.v_venv/bin/python to the path of your python virtual environment.

  3. Then just use the short key to build your script.

When you want to change your virtual environment, just copy its path to the setting file and all done. Maybe the approach seems containing a lots of work, but it works well and convenient.

Guohua Cheng
  • 943
  • 7
  • 15
5

You're looking for custom build systems.

From the menu bar, click Tools -> Build Systems -> New Build System...

Fill out the template it gives and save it under any filename ending in .sublime-build to your User folder.

Here is the documentation for making custom build systems:

https://www.sublimetext.com/docs/3/build_systems.html

I recommend making a custom build system for python scripts, then add variants for each virtual env you want. (see variants https://www.sublimetext.com/docs/3/build_systems.html#option-variants)

One you make a build system, you can switch them from

Tools -> Build Systems

(if not auto detected) and use the Command Palette (default ctrl + shift p) to switch between variants.

The only "gotcha" is the "cmd" parameter to describe what command to run. By default it takes an array of strings to run as a command, but you can use "shell_cmd" instead to just use a string of how you would run it via command line.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Allison
  • 51
  • 1
2

I'm a super newb to Python, pipenv, and especially Sublime Text 3. Couldn't find a simple solution to get me started working with pipenv virtual environment and sublime on Windows 10.

This works really well for someone who doesn't have much systems experience.

My setup:

 Windows 10 Pro
 Python 3.9
 Sublime Text 3
 Dedicated directory for Python virtual environment 'C:Users\username\VirtualEnvs`
 
  1. create a virtual environment using pipenv in a dedicated directory: pipenv install BestPythonPackage
  2. from the dedicated directory run: pipenv shell
  3. get the virtual environment path; while in the shell run: pipenv --venv
  4. open folder in sublime
  5. create new project: Project > Save Project As > "New Project Name"
  6. select "New Project Name".sublime-project from file list in left column
  7. replace contents of that file with the below and save. The path is what you found from running 'pipenv --venv'
{
    "folders":
    [
        {
            "path": "C:\\Users\\username\\.virtualenvs\\PythonEnvs-uKL8m4_g",           
        },
    ],
    
    "build_systems": [
      {
      "name": "PYTHON_PIPENV",
      "cmd": ["python", "$file"],     
      }
    ], 
}
  1. Observe the sublime folder name for your dedicated folder has changed to the name of the virtual environment.

  2. Create a 'hello.py' program from the folder.

  3. build the program with Tools > Build System > "PYTHON_PIPENV" build system now in the list.

Of course, the caveat here is you'd need to do this for any new virtual environment. Some of the other solutions provided will dynamically update. Those were/are over my head at the moment. This is a simple solution.

'folders' section tells sublime what directory to look at 'build_systems' gives a name for the new config, and tells sublime to run 'python' on whatever file you have open.

Dougmill
  • 21
  • 1