Using operator from another context

I would like to use bpy.ops.text.resolve_conflict() from ouside the TEXTEDITOR
but as expected Blenders throws an error.

Is it even possible, to do this?
Can I set the context manually or is it nescecary to have TEXTEDITOR as the active context?

You can override context like this:

1 Like

Thanks! :slight_smile:

1 Like

I dug deeper, because Blender stiil threw some Errors and a hint, that there is a new way to do it.
So I found this:

temp_override(window, area, region, **keywords )
https://docs.blender.org/api/current/bpy.types.Context.html#bpy.types.Context.temp_override

And I was under the impression, it would work like this:


def do_something():
             for window in bpy.context.window_manager.windows:
                screen = window.screen
                for area in screen.areas:
                    if area.type == 'TEXT_EDITOR':
                        with bpy.context.temp_override(window=window, area=area):
                            bpy.ops.text.run_script()
                            break

But the console still says: Nope, context invalid…

unfortunately there is only one reliable way to figure out exactly what the context requirement for a built-in operator is: look at the source code and dig through the operator’s poll function.

Here’s a post I made a while back on how you can go about doing it, even without any C experience (though it certainly helps):

edit: doing a quick scan through the source for text.resolve_conflict, there aren’t really many things you can override here. it’s not looking for a specific window or area, it just requires data to be loaded and ready to go, so if its context is not correct there’s a deeper problem with what you’re trying to do.

a quick rundown:

static bool text_save_poll(bContext *C)
{
  Text *text = CTX_data_edit_text(C);

  if (!text_edit_poll(C)) {
    return 0;
  }

  return (text->filepath != NULL && !(text->flags & TXT_ISMEM));
}

static bool text_edit_poll(bContext *C)
{
  Text *text = CTX_data_edit_text(C);

  if (!text) {
    return 0;
  }

  if (ID_IS_LINKED(text)) {
    // BKE_report(op->reports, RPT_ERROR, "Cannot edit external library data");
    return 0;
  }

  return 1;
}

these are the two relevant poll functions- normally you’d only need to worry about one, but this one has a poll that calls another poll so you have to consider both.

  • first, it’s getting a reference to the text data that is currently loaded in the text editor
  • if the text can’t be edited, the poll fails immediately (IE: the text data is linked from another .blend)
  • if it has no filepath, it cannot be saved

I suspect your context is failing because you don’t actually have the text data loaded, or you’re not in a workspace where text data can be loaded (ie: the modeling workspace, where there is no text editor).

1 Like