Home Download Buy Blog Forum Support

Inline Python interpreter

Inline Python interpreter

Postby CaptainCrowbar on Thu Jun 14, 2012 4:53 am

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: Select all
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:
        exec text
    except Exception as ex:
        error = str(ex)
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__
    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)
Posts: 24
Joined: Tue Aug 02, 2011 4:31 am

Return to Plugin Announcements

Who is online

Users browsing this forum: nadiam02 and 11 guests