Platform = Ubuntu Linux 64 bit, Blender 2.77a

When creating models using bpy-based python scripting, there many times I need to type in the same code in Blender's python console; every time I invoke a new blender session.

For example if something is wrong with objects, I type the following:

for object in bpy.data.object:
    print(object.name + " is at location " + str(object.location)) 

I would like to put this in an xxx.py file I create in a documents folder so when I need to execute it in the Blender python console at each Blender session, all I would need to do is run the .py file ; this will save a lot of repetitive typing.

How do I do this?


  • 3
    $\begingroup$ Note, Blender comes with a template to do just this: Text Editor -> Templates -> Python -> Script Stub $\endgroup$
    – ideasman42
    Apr 20 '16 at 8:55

This is the equivalent to running the script directly, referencing a scripts path from a 2 line text-block.

filename = "/full/path/to/myscript.py"
exec(compile(open(filename).read(), filename, 'exec'))

You might want to reference a script relative to the blend file.

import bpy
filepath = bpy.path.abspath("//myscript.py")
exec(compile(open(filepath).read(), filepath, 'exec'))
  • $\begingroup$ Thank you so much Smart Gnan Online!! This is a great forum! $\endgroup$ Apr 20 '16 at 8:28

Using blender's text editor you can open a script file to read and edit it. The text editor also has a "Run Script" button to easily run the script you are editing.

An open text file can also be run within the python console with

exec(compile(bpy.data.texts['Text'].as_string(), 'textblock', 'exec'))

this has an advantage when debugging as the variables in the script will remain available in the console after it has been run.

Some time back I started using an addon posted on blender artists that adds a menu to the console which lets you run any open text block in blender's python console. You gave me an idea to expand it a bit by adding another menu made from script files in a directory, the addon will now also list the files within a specific directory which will be loaded and run when chosen. You can download the updated addon here.

  • $\begingroup$ thanks for sharing that Idea! It fills in the gap between developing a full blown operator and just an expression typed into the console. Perfect for those quick-n-dirty snippets and stuff which lives just for some weeks, during the work on one scene, but is not worth elaborating into a full-blown piece of code $\endgroup$
    – Ichthyo
    Feb 11 '19 at 1:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.