<type>documentation</type>
<domain>debug</domain>
<id>debugging-embedded-code</id>
<title>Debugging Embedded Python Code</title>
<date>$Date: 2007-09-13 11:28:39 -0400 (Thu, 13 Sep 2007) $</date>
<version>$Revision: 16386 $</version>
<product>per+</product>

Python is designed so it can be embedded into larger applications as a scripting language,
as a way to write high-level code that controls the functionality of that application.
This is common, for example, in applications designed for 2D and 3D animation,
compositing, and rendering, and some game development software. Examples include `Blender
<ref:howtos/blender>`__, `Autodesk Maya <ref:howtos/maya>`__, `NUKE <ref:howtos/nuke>`__,
and `Source Filmmaker <ref:howtos/sfm>`__.

When Python code is run by an embedded interpreter, you may need some extra configuration
to make debugging work properly.  What is needed depends on how the host application 
embeds and invokes Python.

**Single Python Instance**

If the host application is simply creating a single Python instance and reusing it for all
script invocations, setting ``kEmbedded=1`` in ``wingdbstub.py`` will usually be all that
is needed, in addition to adding ``import wingdbstub`` to your code.  

This tells the debugger that complete exit of the debug code does not indicate that Python
has exited as well, so that the debug connection can remain intact between script
invocations.

**Custom Python Thread States**

Some host applications manually create or alter the Python thread states that is used for
each script invocation. This may disable the debugger and/or disconnect the debug process
from the IDE.

To solve this, invoke ``Ensure()`` in the `debugger API <ref:debug/debugger-api>`__, to
reset the debugger for each script invocation::

    import wingdbstub
    wingdbstub.Ensure()

This tells the debugger to ensure that the debug tracer is properly installed and that the
debug process is connected to the IDE, as needed in this particular application.

**Multiple Python Instances**

In other cases where the host application uses an entirely different Python instance for
each invocation, you will need to arrange that the `Debugger API
<ref:debug/debugger-api>`__ function ``ProgramQuit()`` is called before each instance of
Python is destroyed.

In this case, you should leave ``kEmbedded=0`` in ``wingdbstub.py``.  The debugger
will disconnect and reconnect for each script invocation, as if they were separate
debug processes.

You may also need to unset the environment variable ``WINGDB_ACTIVE`` before importing
``wingdbstub``, if this is left in place by the host application. When this is present it
will prevent ``wingdbstub`` from initiating debug in the second or later Python instance
because the debugger will think that debugging is already active.

