11

When I press "run script" with a python script in the Text Editor, it runs, but seems to spawn some new invisible python interpreter. I'd like it to run in the Python Console that I already have open. Is there a way to do this?

As it stands now, I'm copying and pasting from the Editor to the Console, which sure is tedious.

foobarbecue
  • 710
  • 1
  • 6
  • 20
  • http://blenderartists.org/forum/showthread.php?312821-Run-Script-in-PyConsole-%28Menu%29&s=c69ef95a729a45ad03c6a2a7d67d176e There may be some more recent versions, and IIRC @zeffii has something similar too. – batFINGER Apr 11 '16 at 14:41
  • Another addon. Note, that the blender python console uses InteractiveConsole. You might have a look at scripts/modules/console_python.py. – pink vertex Apr 12 '16 at 08:46

3 Answers3

16

In Blender 2.80 and higher, you can use as_module().

Blender Python Console module example

In the above example, an unsaved text editor shows this code:

def myTestFunc():
    print('This is my test function, running')

print('This is my test module, running')

Then, in the Blender Python console on the left, you can import this:

myModule = bpy.data.texts[0].as_module()

Note that since this is my only text file, I've used texts[0] to reference it. If you had multiple, you would reference by name, such as texts["Text"] or similar.

Note that anytime the source code changes, you will have to re-run the as_module() command again to pick up the changes.

Finally, I can call functions from the module I imported, like so:

myModule.myTestFunc()

This uses the variable name that was assigned by the as_module() line, and looks for a named function within that module to call.

emackey
  • 2,746
  • 1
  • 16
  • 24
  • oh I love you.. a one-liner and so simple.. – juggler Apr 25 '22 at 04:02
  • This is a good answer, but kind of a pain in the butt to need to keep running the as_module command. I can't believe that they don't provide a "Run" button to run the script in the context of the interactive python interpreter! – uglycoyote Dec 14 '22 at 04:13
  • @uglycoyote You might know this already, but in the Python console you can press the up-arrow key to recall prior commands, so you don't need to type it out each time. – emackey Dec 19 '22 at 20:13
  • I am looking for something like from myModule import * and I found a solution: globals().update(vars(myModule)) – rint Dec 02 '23 at 15:30
3

In the text editor, make sure that the code you want to run is callable (f.e. make it a function). Name the text datablock something.py). Now you can use import something in the console, and call something.yourfunc() on it.

dr. Sybren
  • 7,139
  • 1
  • 23
  • 52
-3

In Blender go to Window and select toggle system console. Do this after "run script"