Creating 3d renders, games, and animations is always incredibly exciting! Well, except when it gets challenging or tedious. If youâve been using Blender or any other 3D app for a while, youâve found yourself slogging through the same tasks over and over again and at some point thinking, âI really wish Blender just did this for meâ.Â
Through scripting, it can! Not only that, Python can create fun new features that are not even possible by clicking around the interface.Â
If youâre like me and havenât had any training in computer science, programming can seem like a four-letter word except with eleven letters (2.75 times as bad!). Itâs like a secret language that only smart people know, who probably also always read the nutrition facts, build rocket engines for fun, or have a Ph.D. in some type of math that doesnât even use numbers.Â
Thatâs thankfully not the case at all. The truth is, if you can use Ctrl+C and Ctrl+V to copy and paste, you can start making your own Blender Python scripts right away.
Get Used to Seeing Code
Exposure therapy. Progressive desensitization. Call it what you will, but the best way to normalize something that seems weird initially is to see it often enough in the right context.Â
Every action that you take in Blenderâs interface is executed via Python commands. You can check this out for yourself by switching your Timeline to the Info Editor and seeing what it spits out when you go about your normal work.Â
The info editor can be a bit of a firehose, but thereâs something about command lines and such that might be programming heresy but put me at ease when starting out - most of what you see is there just in case you need it and 98% of the time you wonât need it. So when you do something simple like moving the cube and it gives you two or three full lines of code, you can ignore most of it. The important part is right at the beginning:Â
bpy.ops.transform.translate(value = (0.5, 0, 0))
You already know that the name for moving something is called âtranslateâ, so the values that come after that are how much youâve translated your object on the X, Y, and Z axes respectively. Everything before âtranslateâ is where that command is found in Blenderâs code. Itâs as if Blender is one giant nested menu and you selected Blender Python -> Operations -> Transform -> Translate.Â
There are nine main sections of Blender Python (bpy). You donât need to memorize these, but recognizing some of them can help you understand how Blender is working under the hood.
- bpy.app - Information about Blender itself that doesnât change while running.
- bpy.context - Read-only lists of whatâs currently active in Blender.Â
- bpy.data - All of Blenderâs internal data, such as objects.
- bpy.msgbus - Stands for âmessage busâ, and is used for notifying Blender of certain changes. Not something we need to worry about.Â
- bpy.ops - All the operations you can do in Blender, from modeling to appending files to rendering.Â
- bpy.path - Functions that deal with file paths.Â
- bpy.props - The different properties that Blender uses. Youâd use this to tell Blender whether an input should be a number or a color.Â
- bpy.types - Every type of thing that exists in Blender, from modifiers to textures to lamps and much more.
- bpy.utils - Utility functions that are only for Blender but do not deal with internal data.
If youâre curious, here is the API documentation for Blender 2.8 and for all previous versions.Â
As you work, get used to seeing where your favorite tools can be found in the code. You donât need to understand it all at this point - just get used to what it looks like!
The Python Console of Power
Once youâre ready for the next step, head over to the Scripting workspace tab. Youâll find the now-familiar info editor on the bottom left. Directly above that is the Python Console, which is where you can paste commands and make things happen. Try this: select a line in the Info Editor, hit Ctrl+C to copy, and then use Ctrl+V to paste it into the console. Hit enter, and youâll see that exact same action happen again!Â
Now try this: rotate, scale and move something, or do any other three actions in a row. Copy all three from the info editor and paste them into the Console. Now you just did three things at once! Thereâs no limit to this, so you could do hundreds of things at once this way if you wanted. Even if you go no further into coding, this is a great trick to keep in your back pocket. Â
Saving Commands with the Text EditorÂ
Hunting through a bunch of commands and copy / pasting all the time is itself pretty tedious if you do it a lot! Letâs save ourselves some time and make our multitasking even more efficient by using Blenderâs Text Editor.Â
Create a new text file and copy and paste three or more different actions from the info editor into the text editor. Iâll start by adding a cube:Â
bpy.ops.mesh.primitive_cube_add(size=2, view_align=False, enter_editmode=False, location=(0, 0, 0))
Then Iâll rotate the cube along the Z axis:Â
bpy.ops.transform.rotate(value=-0.261911, orient_axis='Z', orient_type='GLOBAL', orient_matrix=((1, 0, 0), (0, 1, 0), (0, 0, 1)), orient_matrix_type='GLOBAL', constraint_axis=(False, False, True), mirror=True, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1)
Yikes, thatâs a lot of code for something so simple! If it doesnât bother you then go ahead and keep it. If you find it intimidating though, try deleting everything except the value and the oriented axis so that it reads easier. The rest will simply assume defaults.Â
bpy.ops.transform.rotate(value=-0.261911, orient_axis='Z')
Lastly, letâs add a bevel modifier:Â
bpy.ops.object.modifier_add(type='BEVEL')
The one extra thing that youâll need to do to get the script to run is type:
import.bpy
At the top of the file, so that it can read Blender Python. Itâs also helpful to switch on the three buttons for line numbers, word wrap, and syntax highlighting in the Text Editorâs header.Â
There you go, you now have a script! You can now do three very important things all at once by clicking Run Script in the Text Editorâs header. If you want to save it for later or use it in a different file, go to Text -> Save As and save it as a .py Python file.Â
If you tried different commands than I did and your script doesnât work as expected, itâs likely due to context - which object is selected or which editor is active. You can select or deselect objects in Blender 2.8 by setting its selection property to True or False:Â
bpy.data.objects['ObjectName'].select_set(state=True)
All Hail AutocompleteÂ
Some commands that Blender has can only be done through code and are not found in the interface. In addition, other things that do change in the interface (like scrubbing the timeline) donât always give you something in the Info Editor that you can copy and paste.Â
You can always use Google or the Blender API Docs to help you find the right command to do what you need, but often itâs easier to just find it using autocomplete. If you start typing an address in the Python Console, you can hit Ctrl+Space and Blender will show you all available ways to complete what youâve written. Itâs a great way to navigate the codebase and discover new features.Â
The Text Editor also has a Ctrl+Space autocomplete feature, but it doesnât work the same and is generally not that helpful. If itâs something youâd use often, Iâd recommend grabbing  Jacques Luckeâs Code Autocomplete addon which will allow you to work much faster.Â
Terrific Templates
If youâd like to turn your script into a proper addon that can be accessed via a button in the interface or a menu, Blenderâs built-in templates are a great place to start. There can be a lot to remember when it comes to how to provide the info thatâs seen in the User Preferences or how to register the addon so that itâs displayed properly, so templates are a great thing to refer to (or copy and paste from) if you get stuck.Â
Actually Learning Python
If youâve enjoyed creating your own scripts but feel a little underwhelmed at their lack of power (I made some big promises at the beginning!), then itâs time to learn more about Python and programming in general. Concepts like variables, loops, and functions are essential to making anything truly new or powerful. A little knowledge can go a long way here, so it really is worth the extra effort. Iâd recommend digging into Python at one of the following sites. We're not affiliated in any way, they just do a good job.
Send Help!
Inevitably, youâll get stuck in the middle of building your own scripts and add-ons. It happens to the best of us! Here are the places you can go to ask questions about coding in Blender:
You can also learn more by watching these courses on CG Cookie:Â
- Intro to Python Scripting in Blender
- Scripting with Python Handler Functions in Blender
- Scripting a Custom Rig UI in Blender
I learned html from having my own website, python shouldn't be too much different.
No seriously, nice post. Self taught using computers (286) and trying to code. Thought DOS was all you needed to code and 1st time like 200 line of code just to have a small menu command screen to switch monitor color from 1 color to another. Then I learn there was like a dozen program languages to code not counting machine language n I was WTF? Too busy working but trying to do/learn Python. Keep up the good work. Been using blender since found out about it Ver. 2.40 or around that time period
Voice command! Blender, display cube. scale x 5, scale z 3.. Subdivide 4X. Add Texture, File Texture Brick image 5, use nodes. Render....lol
Huh, this seems understandable and doable. Someday... ;)
copperplate Ahaha that would be perfect. I'd buy that addon! đ
This is a great article, Jonathan! If there's one thing Blender could do for me automatically, it would be:
import bpy
bpy.ops.artist.unemployed_job_add(pay=3000, difficulty_hard=False, client_demanding=False, workfromhome=True, location=(49°57'26.8"N 97°09'27.5"W))
Great introduction to an interesting topic. I already have a lot of experience with python. But I would love more info about using it in Blender and for making add-ons.