ImportError: No module named 'bge'
Blender Scripts

Pressing the "run script" button makes the code be executed as Blender script. This does not rely to the BGE. Importing the BGE API will always fail with:

ImportError: No module named 'bge'


BGE scripts

BGE Python code gets executed by python controllers. This means in the logic editor you add a python controller. 

The code gets executed when any connected sensor triggers the controller. e.g. by an Always sensor right after loading the object.

Script mode

In Script mode you enter the name of the text block into the value field. The text block will be executed from top to to bottom.

E.g. drawALine

import bge

bge.render.drawLine([0,0,0], [10,10,10], [1,1,1,1]])



Script: drawALine

Module Mode

In Module mode you enter the name of the module (the file name without ".py") with "." which concatenates a function name of the module. The module can be a text block or an external python file that is in the python search path.

E.g. painter.py

import bge

def drawALine(controller):
    bge.render.drawLine([0,0,0], [10,10,10], [1,1,1,1]])


Module: painter.drawALine

Blender API inside the BGE

Using the Blender API bpy inside the BGE will not fail when you run your game embedded in Blender. But any writing to the Blender API will not take effect before ending your game.

When running your game without Blender importing bpy will fail the same way as running BGE scripts inside of Blender:

ImportError: No module named 'bpy'