This is a simple plugin I wrote for running quick and dirty Python scripts while editing. You just write some code, select it, call the script, and the output is inserted into the document. Any error messages it emits are included in the output. It provides two commands, interpret_and_append (which inserts the output into your document after the selected code), and interpret_and_replace (which replaces the selected code with the output). I have them bound to Cmd+Shift+X and Cmd+Option+X on Mac, Ctrl+Shift+X and Ctrl+Alt+X on Windows.
[code]import sublime, sublime_plugin
import re
import sys
import StringIO
def _interpret_python(text, append):
out = StringIO.StringIO()
err = StringIO.StringIO()
sys.stdout = out
sys.stderr = err
results = ]
error = āā
if append:
results.append(text)
try:
exec text
except Exception as ex:
error = str(ex)
finally:
sys.stdout = sys.stdout
sys.stderr = sys.stderr
results.append(out.getvalue())
results.append(err.getvalue())
results.append(error)
return ā\nā.join([s for s in results if s])
class InterpretAndAppendCommand(sublime_plugin.TextCommand):
def run(self, edit):
for sel in self.view.sel():
text = self.view.substr(sel)
text = _interpret_python(text, True)
self.view.replace(edit, sel, text)
class InterpretAndReplaceCommand(sublime_plugin.TextCommand):
def run(self, edit):
for sel in self.view.sel():
text = self.view.substr(sel)
text = _interpret_python(text, False)
self.view.replace(edit, sel, text)
[/code]