# How to programmatically load a python script in Text Editor and launch it

With python API, is it possible to load a (new) python script in the Text Editor and then launch it (to automate things !) ?

I try this but it doesn't work :

bpy.ops.text.open(filepath="my-script.py")
bpy.ops.text.run_script()


Script name added in the text list but not visible in the Editor.

• Where are you running this from? – iKlsR Apr 9 '14 at 16:23
• From command line : \$ blender.exe --python script-to-automate-things.py – Lebrun Apr 9 '14 at 17:54
• My configuration : Blender version 2.69, OS Cygwin on Windows7 – Lebrun Apr 9 '14 at 18:05
• I must add that i just try to simplify the task for my project. Everything loaded and executed and the script ready to be completed in the text editor. – Lebrun Apr 9 '14 at 19:25

Every Text Editor has its own active (visible) text datablock stored in .text.

To call the text.run_script() operator, use a context override and give it the right 'edit_text' member.

import bpy

for area in bpy.context.screen.areas:
if area.type == 'TEXT_EDITOR':
area.spaces[0].text = text # make loaded text file visible

ctx = bpy.context.copy()
ctx['edit_text'] = text # specify the text datablock to execute
ctx['area'] = area # not actually needed...
ctx['region'] = area.regions[-1] # ... just be nice

bpy.ops.text.run_script(ctx)
break

• Just a sidenote: You can also use area.spaces.active.text = text since area.spaces[0] is the active space. – satishgoda Apr 10 '14 at 7:47

It seems it can be done in less code even, just the following code, no TextEditor windows open.

# text = bpy.data.texts.load(path_to_file)   # if from disk
text = bpy.data.texts['some_file_name.py']   # if exists in blend
ctx = bpy.context.copy()
ctx['edit_text'] = text
bpy.ops.text.run_script(ctx)


executed fine!

Another technique is illustrated at http://web.purplefrog.com/~thoth/blender/python-cookbook/exec-text-library.html

import bpy
bufferName = 'lib 1'
lib1 = bpy.data.texts[bufferName].as_string()
exec(lib1)

• this even works when the script being exec'd is importing local datablock .py files as modules. nice. – zeffii Jun 16 '15 at 17:04
• this can fail if the file you are trying to exec has a few imports not already present in globals/locals -- and this isn't being executed directly from the TextEditor. – zeffii Nov 14 '15 at 13:27

You don't necessary need to load it. You can use a browser to get the path p and then run exec(compile(open(p).read(), p, 'exec')). The script will be executed.