Double Dash (–) For Passing Arguments From Blender To Python

Invoking Python from Blender

Blender provides integrated Python scripting for advanced users to automate workflows and customize tools. The “–” operator is used to pass data from Blender directly into a Python script executed from the Blender interface.

To invoke a Python script, navigate to the Text Editor and create a new text block. Write the Python code here and save it with a .py extension. From any Blender window, type the script name preceded by two hyphens to execute it.

For example, if the script is named my_script.py, typing “– my_script” will run the code. Any arguments after the script name are passed into the Python namespace.

Using the “–” operator to pass arguments

The double dash signals Blender to treat the text that follows as a Python script path and parameters rather than a built-in command. Any values provided after the script name can be read by the Python code to parametrize its operations.

For example, -- my_script cube sphere 20 would run my_script.py, passing “cube”, “sphere”, and 20 as arguments. These can be retrieved using import sys and sys.argv in Python.

Common uses for the “–” operator include:

  • Passing the names of Blender objects to operate on
  • Specifying property values to assign
  • Providing file system paths to read or write
  • Controlling iterations or recursion depth

Any valid Python syntax can follow the script name using the “–” syntax. By leveraging this functionality, technical Blender users can build flexible workflows and tools.

Accessing Blender Data in Python

The Blender Python API provides complete programmatic access to Blender’s internal data structure. This allows scripts to inspect and modify the scene, objects, materials, textures, and more. Common starting points for accessing data include:

  • bpy.context – Current context like active object or edit mode
  • bpy.data – Blender data blocks like objects, meshes, etc.
  • bpy.ops – Wrapper for calling Blender operators

Obtaining references to Blender objects

The most common task for Python integration is to operate on Blender object data. The bpy.data.objects collection contains all objects in the current scene:

cube = bpy.data.objects["Cube"]  
objects = [o for o in bpy.data.objects if o.type == "MESH"]

Alternatively, the context’s selected_objects can be accessed without knowing names:

for obj in bpy.context.selected_objects:
    print(obj.name)

These references grant complete access to each object’s properties and datablocks like meshes, materials, particle systems, etc.

Querying and modifying object properties

Common object properties include location, rotation, scale, visibility, display type, parenting, constraints, modifiers, and materials. These can be read and updated to programmatically alter the scene.

# Set object location
cube.location = (1.0, 2.0, 3.0)  

# Add Subsurf modifier at level 2
mod = cube.modifiers.new("Subsurf", type='SUBSURF') 
mod.levels = 2

# Toggle viewport visibility
cube.hide_viewport = not cube.hide_viewport

Custom properties can also be added to store metadata like annotations or cache data for scripted workflows.

Command line arguments

In addition to the “–” operator, external command line arguments can be passed directly to Python scripts when launching Blender from a shell or terminal.

Reading sys.argv in the Python script

The sys module provides access to command line arguments from environment variables. Its argv attribute is a list of argument strings passed to the script.

import sys

object_name = sys.argv[1]
subdiv_level = int(sys.argv[2])

Note that sys.argv[0] contains the path of the script file itself. Subsequent indices contain arguments passed from the command line in order.

Parsing command line arguments

For more advanced argument processing, dedicated parsers such as argparse can be used:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-o", "--object", required=True, help="Object to modify")  
parser.add_argument("-s", "--subdivisions", type=int, default=1, 
                    help="Number of subdivisions")
                    
args = parser.parse_args()                   
object = bpy.data.objects[args.object]
subdiv_level = args.subdivisions

This approach handles data types, required versus optional arguments, help text and error handling.

Usage examples

Here are some examples combining “–” arguments, Python scripting and command line parameters to demonstrate practical applications.

Simple property query

Print names and locations of all visible mesh objects in the scene:

import bpy

for o in bpy.data.objects:
    if o.type == 'MESH' and o.visible_get(): 
        print(o.name, o.location) 
        
print("-- Finished --")

Invoke from Blender with:

-- query_mesh_locations.py

Batch process multiple objects

Script to subdivision smooth and displace a list of objects passed as arguments:

import sys
import bpy

objects = sys.argv[1:]

for o in objects:
    obj = bpy.data.objects[o]  
    mod = obj.modifiers.new("Subsurf", type='SUBSURF')
    mod.levels = 2
    
    mod = obj.modifiers.new("Displace", type='DISPLACE') 
    mod.strength = 0.25
    
print(f"-- Modified {len(objects)} objects --")

Run from the command line, passing object names:

blender --background --python displace_script.py Cube Sphere Cylinder

Automate repetitive tasks

Script to duplicate multiple copies of an object with incremental transforms:


import sys
import bpy
  
name = sys.argv[1]  
count = int(sys.argv[2])
offset = float(sys.argv[3])
  
obj = bpy.data.objects[name]

for i in range(count):
    copy = obj.copy()
    copy.location[0] += i * offset 
    bpy.context.scene.collection.objects.link(copy)   
    
print(f"-- Duplicated {name} {count} times --") 

Run it from the “–” prompt:

-- duplicate_objects.py Suzanne 10 2

Integrations and Applications

The programmatic Blender/Python link enables deeper technical pipelines as well as rapid iteration for artists and designers.

Connecting Blender and Python Pipelines

Python allows integrating Blender into complex workflows either as an import/export frontend or automated backend. Some examples include:

  • Procedural object generation with math/physics libraries
  • Physical simulation and analysis data imports
  • Programmatic animation via physics engines like Bullet
  • Exporting edits from Blender back into procedural state

For largescale batch operations, Blender can be driven headless from the command line without tying up the UI.

Potential Use Cases and Limitations

Scripting excels at automating repetitive tasks or connecting multiple domains. Artists can focus on designing assets rather than technical tools.

However, Python interaction has a higher learning curve and may not suit all users. Performance can lag compared to core C/C++ code. Stability issues may arise from poorly coded scripts.

When applied judiciously, though, Python scripting unlocks tremendous potential from Blender as a creative tool.

Leave a Reply

Your email address will not be published. Required fields are marked *