3
$\begingroup$

I'm just getting started with bpy and I wish to know how can I execute the addon below from the console.

# hello_world.py
bl_info = {
    "name": "Hello World",
    "category": "Object",
}
import bpy
class HelloWorld(bpy.types.Operator):
    """Print in the System Console"""
    bl_idname = "object.hello_world"
    bl_label = "Hello World"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context):
        print("Hello, world!")
        return {'FINISHED'}

def register():
    bpy.utils.register_class(HelloWorld)

def unregister():
    bpy.utils.unregister_class(HelloWorld)

I tried:

import hello_world
hello_world = hello_world.HelloWorld
hello_world
>>> <class 'hello_world.HelloWorld'>
hello_world.execute
>>> <function HelloWorld.execute at 0x0000009F05C576A8>

But it did not really execute. Whatever if it is a print function or an object translation it did not execute. What am I doing wrong?

I can execute the script from the space bar, typing the label Hello World but I wish to call a variable from an addon and use it in a different addon. Thanks!

$\endgroup$

2 Answers 2

4
$\begingroup$

But it did not really execute.

Based on my understanding of Blender, an operator cannot be directly executed. It should be called from Blender internal.

Try bpy.ops.object.hello_world() Where hello_world is the name you registered to Blender system using bl_idname.

More details if you are interested:

When a request of operator invoking is arrived, Blender internal(the source code looks like a factory) will create an Operator instance dynamically, and call your execute function there. You should not call it yourself IMO.

but I wish to call a variable from an addon and use it in a different addon

In your case I think you may want to have some utility functions shared with other addons. I suggest to write these utility functions as normal Python function and pass the context to it from your addons.

$\endgroup$
0
$\begingroup$

If you need to run something in console programmatically then you have to override context to 'CONSOLE' area, then you will be able to call bpy.ops.console.execute():

console_area = next(area for area in bpy.context.screen.areas if area.type == 'CONSOLE')
override = bpy.context.copy()
override['area'] = console_area
override['region'] = next(region for region in console_area.regions if region.type == 'WINDOW')
with bpy.context.temp_override(**override):
    bpy.ops.console.clear_line()
    bpy.ops.console.insert(text='print("hello")')
    bpy.ops.console.execute()
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .