How to import and run external scripts?

You are right there is no pure python logic. If you need that I suggest to switch to Panda3d.

In Blender you can use the Python controller in module mode. With that you can call functions in that form:

<modulename>.<function>
e.g.
testmodule.main

calls:
main() from file testmodule.py

The file can be internal or external. The module search path includes the current folder. If both are present the external file will be used. So it is important to keep them synchronized (<ALT-S> in text window).

If you want to keep the scripts in one folder there are two options:

  1. place your file in the directory “scripts” (within the blend directory ). Add a python file “init.py” that imports all modules from that directory . Set the python module controller to “scripts.testmodule.main”

  2. expand the module search path by placing this code on top of a script:

import sys
scriptFolder = GameLogic.expandPath('//scripts')
if not scriptFolder in sys.path:
    sys.path.append(GameLogic.expandPath('//scripts'))

Make sure the script is executed before importing any other module from the scripts directory.

I hope it helps

1 Like