7

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.

Lebrun
  • 131
  • 2
  • 3

4 Answers4

10

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

text = bpy.data.texts.load(path_to_file)

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
CodeManX
  • 29,298
  • 3
  • 89
  • 128
  • 2
    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 07:47
7

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!

zeffii
  • 39,634
  • 9
  • 103
  • 186
3

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)
Mutant Bob
  • 9,243
  • 2
  • 29
  • 55
  • 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
0

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.

Ray Mairlot
  • 29,192
  • 11
  • 103
  • 125