9

How can I import a Blender Python script inside another? I am working a python file using blender api named - generate.py, which contains some functions. I want to call those functions in another file called test.py.

I opened both the files in the blender text editor and on top of the test.py file, I wrote from generate import *, but when I call a function defined inside generate.py in test.py, I get an error saying module named generate.py does not exist. So what is the right way to define modules in blender. I also have both the files in the same directory

Duarte Farrajota Ramos
  • 59,425
  • 39
  • 130
  • 187
sreesreenu
  • 361
  • 1
  • 2
  • 10
  • possible duplicate of http://blender.stackexchange.com/questions/33603/importing-python-modules-and-text-files/33622 – Mutant Bob Apr 19 '16 at 19:52

2 Answers2

14

The issue was that the path of the python module - generate.py was not in the locations where python searches for modules. To make generate.py visible to python add the following code on top of test.py

import bpy
import sys
import os

dir = os.path.dirname(bpy.data.filepath)
if not dir in sys.path:
    sys.path.append(dir )

import generate

# this next part forces a reload in case you edit the source after you first start the blender session
import imp
imp.reload(generate)

# this is optional and allows you to call the functions without specifying the package name
from generate import *
sreesreenu
  • 361
  • 1
  • 2
  • 10
4

The above ability was removed in 2.8.

From 2.8 the method is as below. I used this in Blender 2.9.

my_module = bpy.data.texts["my_module"].as_module()

Release Note:

https://wiki.blender.org/wiki/Reference/Release_Notes/2.80/Python_API#Importing_Text

Duarte Farrajota Ramos
  • 59,425
  • 39
  • 130
  • 187
  • This works, thanks, but error messages within the modules (i.e. stack backtraces) become very sparse. They call the imported modules just "module" and only mention the topmost file, not the included files. Makes bug fixing quite annoying... – Germanunkol Sep 25 '21 at 20:22