Adds a button that takes whatever's in the Text Editor and runs it in the Console

This is a little addon I made today based off of this one by CoDEmanX, however I made it a little simpler and quicker.

In short, I’m used to coding in Visual Studio Code which has a quick little ‘run’ button that runs your whole code in a console displayed within the program interface so you don’t need to click between multiple tabs. I found when coding with Blender, I was annoyed that in order to see the actual output of my code I had to click back and forth between my main window and the Prompt window.

What this addon does is create a button in the header of the Python Console that when pressed will take the text currently entered into the Text Editor and run it as python code in the Python Console. Feel free to just copy the code directly.

bl_info = {
    "name": "Run Text File in PyConsole",
    "author": "Fez_Master (with some components taken from CoDEmanX)",
    "version": (1, 0),
    "blender": (3, 1, 2),
    "location": "Console Header",
    "description": "Execute the code in the Text Editor within the python console.",
    "warning": "",
    "wiki_url": "",
    "tracker_url": "",
    "category": "Development"}

import bpy

def main(self, context):
    '''Fetches text from text editor, formats it, then runs in console'''
    for area in context.screen.areas:
        if area.type == 'TEXT_EDITOR':
            text = area.spaces[0].text
            break
    if text is not None:
        text = "exec(compile(" + repr(text) + ".as_string(), '" + text.name + "', 'exec'))"
        bpy.ops.console.clear_line()
        bpy.ops.console.insert(text=text)
        bpy.ops.console.execute()

class CONSOLE_OT_run_file(bpy.types.Operator):
    bl_idname = 'console.run_file'
    bl_label = ''
    bl_description = 'Run Current Text File in Console'
    
    text = bpy.props.StringProperty()
    
    def execute(self, context):
        main(self, context)
        return {'FINISHED'}

def draw_item(self, context):
    self.layout.operator(CONSOLE_OT_run_file.bl_idname, icon='FILE_SCRIPT')

def register():
    bpy.utils.register_class(CONSOLE_OT_run_file)
    bpy.types.CONSOLE_HT_header.append(draw_item)
    
def unregister():
    bpy.types.CONSOLE_HT_header.remove(draw_item)
    bpy.utils.unregister_class(CONSOLE_OT_run_file)

if __name__ == "__main__":
    register()

If anyone has any suggestions, I would love to hear it!

1 Like

I did something similar with my addon I created for my workflow, I can select a text block and run it, or load a script from disk. Also have some other functions on it I use a lot, so everything is in one place.
By all means rummage through the code and see if anything is of use.
https://drive.google.com/file/d/1_wJCfIvN8LrH12ZpmNAuN1UCZjxoUhKG/view?usp=sharing

1 Like