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$

1 Answer 1

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
$\endgroup$
2
  • $\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
    Commented May 19, 2015 at 11:43
  • $\begingroup$ Your render.py file is being loaded from disk? I don't think your question made that clear. $\endgroup$
    – zeffii
    Commented May 19, 2015 at 12:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .