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:
        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)
CaptainCrowbar
 
Posts: 24
Joined: Tue Aug 02, 2011 4:31 am

Return to Plugin Announcements

Who is online

Users browsing this forum: No registered users and 10 guests