Page MenuHome

When switching scenes using "-S" argument in command line, scripts called by "--python-text" do not get correct scene context
Closed, ResolvedPublic

Description

Version: 2.79b (linux 64)

How to reproduce:

  1. Open the file active_scene_api.blend and inspect the embedded python script.
  2. Close blender.
  3. Open the same file from the command line and execute the script like so: blender -b active_scene_api.blend --python-text "active_scene.py"
  4. Observe the output from the script.
  5. Now do the same, but change the scene using the scene argument: blender -b active_scene_api.blend -S "Scene B" --python-text "active_scene.py"
  6. Note how it does not print the current active scene name, but instead prints whatever the active scene was when the file was saved.

This can cause errors and unexpected behavior with render scripts.

Event Timeline

Bastien Montagne (mont29) triaged this task as Confirmed, Medium priority.

Took me some time to understand what is happening here… thing is, we do some backup/sanitizing of context before executing py scripts, and among other things, arg_py_context_backup calls CTX_wm_window_set, which sets again context's Scene from active windows' screen scene…

@Campbell Barton (campbellbarton) think you are familiar with this area of the code, not sure what is the best/correct solution here. :/

Thank you @Bastien Montagne (mont29) . I did discover a workaround which was to wrap the script in a function that is appended to the app handlers. Consider the following script:

import bpy

def print_scene(dummy):
    scene = bpy.context.scene
    print("The active scene is " + scene.name + "... or is it?")
    
bpy.app.handlers.render_init.append(print_scene)

When called from bpy.app.handlers. render_init, the context is correct. Perhaps this is a better way to do it anyway, but as a matter of principle it still seems better to make sure that the context is consistent, and called from something other than the active window screen screen, since the screen isn't always there!