6 Here are various suggestions that you might find useful when writing scripts.
8 Some of these are just Python features that scripters may not have thought to use with Blender,
9 others are Blender specific.
17 When writing Python scripts, it's useful to have a terminal open,
18 this is not the built-in Python console but a terminal application which is used to start Blender.
20 There are 3 main uses for the terminal, these are:
22 - You can see the output of ``print()`` as your script runs, which is useful to view debug info.
23 - The error trace-back is printed in full to the terminal which won't always generate an error popup in
24 Blender's user interface (depending on how the script is executed).
25 - If the script runs for too long or you accidentally enter an infinite loop,
26 :kbd:`Ctrl-C` in the terminal (:kbd:`Ctrl-Break` on Windows) will quit the script early.
30 For Linux and OSX users this means starting the terminal first, then running Blender from within it.
31 On Windows the terminal can be enabled from the help menu.
38 Access Operator Commands
39 ------------------------
41 You may have noticed that the tooltip for menu items and buttons includes the ``bpy.ops.[...])`` command
42 to run that button, a handy (hidden) feature is that you can press :kbd:`Ctrl-C` over
43 any menu item/button to copy this command into the clipboard.
49 To find the path from an :class:`ID` datablock to its setting isn't always so simple since it may be nested away.
50 To get this quickly you can right click on the setting and select select **Copy Data Path**,
51 if this can't be generated, only the property name is copied.
55 This uses the same method for creating the animation path used by
56 :class:`bpy.types.FCurve.data_path` and
57 :class:`bpy.types.DriverTarget.data_path` drivers.
60 .. _info_show_all_operators:
65 While Blender logs operators in the Info space,
66 this only reports operators with the ``REGISTER`` option enabeld so as not to flood the *Info* view
67 with calls to ``bpy.ops.view3d.smoothview`` and ``bpy.ops.view3d.zoom``.
69 However, for testing it can be useful to see **every** operator called in a terminal,
70 do this by enabling the debug option either by passing the ``--debug-wm`` argument when starting Blender
71 or by setting :mod:`bpy.app.debug_wm` to ``True`` while Blender is running.
74 Use an External Editor
75 ======================
77 Blenders text editor is fine for small changes and writing tests but its not full featured,
78 for larger projects you'll probably want to use a standalone editor or Python IDE.
80 Editing a text file externally and having the same text open in Blender does work but isn't that optimal
81 so here are 2 ways you can easily use an external file from Blender.
83 Using the following examples you'll still need textblock in Blender to execute,
84 but reference an external file rather then including it directly.
87 Executing External Scripts
88 --------------------------
90 This is the equivalent to running the script directly, referencing a scripts path from a 2 line text-block.
92 .. code-block:: python
94 filename = "/full/path/to/myscript.py"
95 exec(compile(open(filename).read(), filename, 'exec'))
98 You might want to reference a script relative to the blend file.
100 .. code-block:: python
105 filename = os.path.join(os.path.dirname(bpy.data.filepath), "myscript.py")
106 exec(compile(open(filename).read(), filename, 'exec'))
112 This example shows loading a script in as a module and executing a module function.
114 .. code-block:: python
123 Notice that the script is reloaded every time, this forces use of the modified version,
124 otherwise the cached one in ``sys.modules`` would be used until Blender was restarted.
126 The important difference between this and executing the script directly is it
127 has to call a function in the module, in this case ``main()`` but it can be any function,
128 an advantage with this is you can pass arguments to the function from this
129 small script which is often useful for testing different settings quickly.
131 The other issue with this is the script has to be in Pythons module search path.
132 While this is not best practice - for testing you can extend the search path,
133 this example adds the current blend files directory to the search path, then loads the script as a module.
135 .. code-block:: python
141 blend_dir = os.path.dirname(bpy.data.filepath)
142 if blend_dir not in sys.path:
143 sys.path.append(blend_dir)
154 While developing your own scripts Blenders interface can get in the way,
155 manually reloading, running the scripts, opening file import etc. adds overhead.
157 For scripts that are not interactive it can end up being more efficient not to use
158 Blenders interface at all and instead execute the script on the command line.
162 blender --background --python myscript.py
165 You might want to run this with a blend file so the script has some data to operate on.
169 blender myscene.blend --background --python myscript.py
174 Depending on your setup you might have to enter the full path to the Blender executable.
177 Once the script is running properly in background mode, you'll want to check the output of the script,
178 this depends completely on the task at hand however here are some suggestions.
180 - render the output to an image, use an image viewer and keep writing over the same image each time.
181 - save a new blend file, or export the file using one of Blenders exporters.
182 - if the results can be displayed as text - print them or write them to a file.
185 While this can take a little time to setup, it can be well worth the effort
186 to reduce the time it takes to test changes - you can even have
187 Blender running the script every few seconds with a viewer updating the results,
188 so no need to leave your text editor to see changes.
194 When there are no readily available Python modules to perform specific tasks it's
195 worth keeping in mind you may be able to have Python execute an external command
196 on your data and read the result back in.
198 Using external programs adds an extra dependency and may limit who can use the script
199 but to quickly setup your own custom pipeline or writing one-off scripts this can be handy.
203 - Run The Gimp in batch mode to execute custom scripts for advanced image processing.
204 - Write out 3D models to use external mesh manipulation tools and read back in the results.
205 - Convert files into recognizable formats before reading.
208 Bundled Python & Extensions
209 ===========================
211 The Blender releases distributed from blender.org include a complete Python installation on all platforms,
212 this has the disadvantage that any extensions you have installed in your systems Python wont be found by Blender.
214 There are 2 ways around this:
216 - remove Blender Python sub-directory, Blender will then fallback on the systems Python and use that instead
219 The Python version must match the one that Blender comes with.
221 - copy the extensions into Blender's Python sub-directory so Blender can access them,
222 you could also copy the entire Python installation into Blenders sub-directory,
223 replacing the one Blender comes with.
224 This works as long as the Python versions match and the paths are created in the same relative locations.
225 Doing this has the advantage that you can redistribute this bundle to others with Blender and/or the game player,
226 including any extensions you rely on.
229 Drop Into a Python Interpreter in Your Script
230 =============================================
232 In the middle of a script you may want to inspect some variables,
233 run some function and generally dig about to see whats going on.
235 .. code-block:: python
238 code.interact(local=locals())
241 If you want to access both global and local variables do this...
243 .. code-block:: python
246 namespace = globals().copy()
247 namespace.update(locals())
248 code.interact(local=namespace)
251 The next example is an equivalent single line version of the script above which is easier to paste into your code:
253 .. code-block:: python
255 __import__('code').interact(local=dict(globals(), **locals()))
258 ``code.interact`` can be added at any line in the script
259 and will pause the script an launch an interactive interpreter in the terminal,
260 when you're done you can quit the interpreter and the script will continue execution.
263 If you have **IPython** installed you can use its ``embed()`` function which uses the current namespace.
264 The IPython prompt has auto-complete and some useful features that the standard Python eval-loop doesn't have.
266 .. code-block:: python
272 Admittedly this highlights the lack of any Python debugging support built into Blender, but its still handy to know.
276 This works in the game engine as well, it can be handy to inspect the state of a running game.
286 From a Python perspective it's nicer to have everything as an extension
287 which lets the Python script combine many components.
291 - you can use external editors/IDE's with Blenders Python API and execute scripts within the IDE
292 (step over code, inspect variables as the script runs).
293 - editors/IDE's can auto complete Blender modules & variables.
294 - existing scripts can import Blender API's without having to run inside Blender.
297 This is marked advanced because to run Blender as a Python module requires a special build option.
299 For instructions on building see
300 `Building Blender as a Python module <http://wiki.blender.org/index.php/User:Ideasman42/BlenderAsPyModule>`_
303 Python Safety (Build Option)
304 ----------------------------
306 Since it's possible to access data which has been removed (see Gotcha's),
307 this can be hard to track down the cause of crashes.
309 To raise Python exceptions on accessing freed data (rather then crashing),
310 enable the CMake build option WITH_PYTHON_SAFETY.
312 This enables data tracking which makes data access about 2x slower
313 which is why the option isn't enabled in release builds.