Instantly share code, notes, and snippets.

Embed
What would you like to do?
Use Sublime and Spyder together in a REPL-like fashion

Running a Python script or selected code from Sublime in Spyder's IPython console

A supplement to the Brushing Up Science post: Invest in a good text editor

I like to use both Python and Sublime Text. But I also like Spyder as a Python IDE. Therefore, although I edit in Sublime, to run scripts or evaluate lines of code in a REPL-like fashion, I do so via Spyder. Detailed below is how I achieve this in such a way that if I want to run the file or evaluate the selected lines, I simply press Shift + Enter.

This example works for Linux using Autokey. For Windows instructions, click here.

Step 1: Autokey code

In AutoKey, save the code below as "Spyder Run File" (note that this file name is referenced in step 2).

# Copy file path using shortcut defined in the sublime-keymap below
keyboard.send_keys('<super>+o')
# Switch to the Spyder Window
window.activate('Spyder (Python 3.5)')
time.sleep(0.1)
# Focus the IPython Console
keyboard.send_keys('<ctrl>+<shift>+i')
time.sleep(0.1)
# Past the path copied from Sublime surrounded by runfile('  '), a command defined in Spyder
keyboard.send_keys('runfile("')
time.sleep(0.1)
keyboard.send_keys('<ctrl>+v')
time.sleep(0.1)
keyboard.send_keys('")')
time.sleep(0.1)
keyboard.send_keys('<enter>')

Save a second file entitled "Spyder Run Lines" with the following content:

# Copy file path using shortcut defined in the sublime-keymap below
keyboard.send_keys('<ctrl>+c')
time.sleep(0.2)
# Switch to the Spyder Window
window.activate('Spyder (Python 3.5)')
time.sleep(0.1)
# Focus the IPython Console
keyboard.send_keys('<ctrl>+<shift>+i')
time.sleep(0.1)
# Past and evaluate
keyboard.send_keys('<ctrl>+v')
keyboard.send_keys('<enter>')

Step 2: Sublime Text preferences

In Sublime Text, add the following to the User Keymap (Preferences > Key Bindings)

(Note that "super+o" is an arbitrary shortcut that is unlikely to be in use, but required in the AutoKey files above)

{
    "keys": ["super+o"], 
    "command": "copy_path"
},
{
    "keys": ["shift+enter"],
    "command": "exec",
    "args": {"cmd": ["autokey-run", "-s", "Spyder Run File"]},
    "context": [{"key": "selector", "operator":
                 "equal", "operand": "source.python"}]
},
{
    "keys": ["shift+enter"],
    "command": "exec",
    "args": {"cmd": ["autokey-run", "-s", "Spyder Run Lines"]},
    "context": [{"key": "selection_empty",
                 "operator": "equal",
                 "operand": false},
                {"key": "selector",
                 "operator": "equal",
                 "operand": "source.python"}]
}

The file above will need square brackets around the file if nothing else exists in the keymap file. See the default keymap for an example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment