Skip to content

Instantly share code, notes, and snippets.

@Andrej730
Last active July 14, 2023 08:50
Show Gist options
  • Save Andrej730/319152c2aac39677c5aafcddf85916fc to your computer and use it in GitHub Desktop.
Save Andrej730/319152c2aac39677c5aafcddf85916fc to your computer and use it in GitHub Desktop.
Run scripts in Python Console Blender addon
# got it from
# https://blender.stackexchange.com/questions/5394/is-there-anyway-to-make-blender-print-errors-in-the-ui
import bpy
bl_info = {
"name": "Run scripts in Python Console",
"author": "CoDEmanX",
"version": (1, 0),
"blender": (2, 80, 0),
"location": "Python Console > Console > Run Script",
"description": "Execute the code of a textblock within the Python Console.",
"warning": "",
"wiki_url": "",
"tracker_url": "",
"category": "Development"}
def get_texts(context):
l = []
for area in context.screen.areas:
if area.type == 'TEXT_EDITOR':
text = area.spaces.active.text
if text is not None:
l.append(text.name)
return l
class CONSOLE_OT_run_script(bpy.types.Operator):
"""Run a text datablock in Python Console"""
bl_idname = "console.run_code"
bl_label = ""
text : bpy.props.StringProperty()
@classmethod
def poll(cls, context):
return context.area.type == 'CONSOLE'
def execute(self, context):
text = bpy.data.texts.get(self.text)
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()
return {'FINISHED'}
class CONSOLE_MT_run_script(bpy.types.Menu):
"""Run a text datablock in Python Console"""
bl_idname = "CONSOLE_MT_run_script"
bl_label = ""
bl_description = "Run script"
def draw(self, context):
layout = self.layout
texts = get_texts(context)
if texts == []:
layout.label(text="No scripts found")
for t in texts:
layout.operator(CONSOLE_OT_run_script.bl_idname, text=t).text = t
def draw_func(self, context):
self.layout.menu(CONSOLE_MT_run_script.bl_idname, icon="PLAY")
classes = (
CONSOLE_MT_run_script,
CONSOLE_OT_run_script,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.CONSOLE_HT_header.append(draw_func)
def unregister():
for cls in classes:
bpy.utils.unregister_class(cls)
bpy.types.CONSOLE_HT_header.remove(draw_func)
if __name__ == '__main__':
register()
#unregister()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment