3
$\begingroup$

I have two files in a directory: "render.py" and "functions.py". From blender I use the text editor to run the "render.py" but the question is how to import "functions.py" to the file. This code fails.

import functions

How can I import in blender so that i can use functions from "functions.py" ?

$\endgroup$
2
$\begingroup$

As a textblock

One way to do this is to add functions.py as a Text block. Make sure the Text block has a .py extension and you can import it directly using import functions. Described here: python-is-it-possible-to-import-another-text-block

As a module

Otherwise, add functions.py to scripts/modules/some_name/functions.py, then

from some_name import functions

A slight hack

There's probably an elegant way to do this, but if your stuck...

The render.py could load functions.py from a given path into a text block named the same:

# render.py #

import bpy   

fp = '/home/zeffii/Desktop/functions.py'

def make_functions_local(fp):
    texts = bpy.data.texts
    t = texts.get('functions.py')
    if not t:
        t = texts.new('functions.py')

    with open(fp) as module_file:
        t.from_string(module_file.read()) 

# trigger it
make_functions_local(fp)

import functions

# your stuff
| improve this answer | |
$\endgroup$
  • $\begingroup$ Well the answer is almost there but the only thing is I would like to avoid putting files into /scripts/smodules/ directory. The perfect answer would be how to import the file in the same directory as the main script. $\endgroup$ – luke1985 May 19 '15 at 11:43
  • $\begingroup$ Your render.py file is being loaded from disk? I don't think your question made that clear. $\endgroup$ – zeffii May 19 '15 at 12:17

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.