Welcome back! If you missed the first installment of Python Editing for Blender, it was mostly about getting set up and adding keyword completion to PyCharm.
Run a Python file through Blender’s interpreter
First up, let’s get something working. Make a directory somewhere and create a file called “HelloWorld.py”.
Let’s start small. Add these lines to the file:
print("Hello, Blender. It's awfully big in here")
Save the file, and now we can run it with Blender’s Python.
You could type this:
C:\Projects\BlenderPythonTutorial>"c:\Program Files\Blender Foundation\Blender\blender.exe" --background --python HelloWorld.py
but that looks terrible. Let’s add Blender to the system path so we don’t have to type so much. We could add it by right-clicking on “Computer”, selecting “Properties”, then “Advanced System Settings”, then finding “Environment Variables” near the bottom of that screen, and so on, but that could be dangerous and is definitely un-user-friendly.
You probably don’t need to run Blender from the command line every day (not yet, anyway), so let’s just make a batch file for updating your path in the terminal. Make another file called initialize.bat and put this in it:
set PATH=%PATH%;"C:\Program Files\Blender Foundation\Blender"
Then just run that in your terminal:
Your output will vary, but you should see the Blender directory at the end. We might put other terminal initialization stuff here later.
Check to see that you don’t have anything weird in your path, like references to malicious-sounding directories you’ve never heard of, and let’s move on.
You can add ‘@’ to the beginning of that line to keep that output from muddying up your terminal. Like so:
@set PATH=%PATH%;"C:\Program Files\Blender Foundation\Blender"
Now you can run this much nicer command-line command:
C:\Projects\BlenderPythonTutorial>blender --background --python HelloWorld.py
And you should get output similar to this:
Read new prefs: C:\Users\jkersey\AppData\Roaming\Blender Foundation\Blender\2.68\config\userpref.blend found bundled python: c:\Program Files\Blender Foundation\Blender\2.68\python Hello, Blender. It's awfully big in here Blender quit
Please note: when you close the terminal, this addition to your path disappears.
So: Blender loads your preferences file, then parses the Python file you just made.
You are now, as they say, “in”.
But what’s in there?
Stay tuned for Python Editing for Blender (Part Three) to find out!
or, check out
BlenderSpriter which is the experiment that inspired this series.