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 Windows using AutoHotKey. For Linux instructions, click here.
An AutoHotKey file is simply a text file with a .ahk extension. Save the code below into a file named spyder_run_file.ahk. In part 2, I assume that this file is saved in my Documents folder.
Send #+o ; Super + Shift + o is the "copy_path" shortcut used in part 2
Sleep 100
WinActivate, Spyder
Sleep 100
StringReplace, clipboard, clipboard, \, /, All ; Convert to unix-like path string (maybe not necessary)
Sleep 100
Send ^+i ; Ctrl + Shift + i is default shortcut to switch to Ipython console
Sleep 100
SendRaw runfile(' ; runfile is a function defined in Spyder
Sleep 100
Send ^v ; Paste the filename that's now currently in the clipboard
Sleep 100
SendRaw ')
Sleep 10
Send {Enter}
Save a second file entitled "spyder_run_selection.ahk" with the following content:
Send ^c
Sleep 100
WinActivate, Spyder
Sleep 100
Send ^+i ; Ctrl + Shift + i is default shortcut to switch to Ipython console
Sleep 100
Send ^v
Sleep 100
Send {Enter}
In Sublime Text, add the following to the User Keymap (Preferences > Key Bindings)
(Note that "super+shift+o"
is an arbitrary shortcut that is unlikely to be in use, but required in one of the AutoHotKey files above)
Be sure to change the file paths for the AutoHotKey scripts. I've left C:/Users/Ken/Documents/spyder_run_file.ahk
in as an example.
{
"keys": ["super+shift+o"],
"command": "copy_path"
},
{
"keys": ["shift+enter"],
"command": "exec",
"args": {"cmd": ["C:/Program Files/AutoHotKey/AutoHotKey.exe", "C:/Users/Ken/Documents/spyder_run_file.ahk"]},
"context": [{"key": "selector", "operator":
"equal", "operand": "source.python"}]
},
{
"keys": ["shift+enter"],
"command": "exec",
"args": {"cmd": ["C:/Program Files/AutoHotKey/AutoHotKey.exe", "C:/Users/Ken/Documents/spyder_run_selection.ahk"]},
"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.
Hi, do the file, as they are, support the execution of code blocks, the same way Ctrl+Return operate in Spyder?