It's advisable to access objects via context members (bpy.context) since most of the available functions a.k.a operators as well as entire UI is based on the current context by design. You can either use C.object, C.active_object (both are interchangeable) or access all selected objects using C.selected_objects. Make sure the object is selected in the viewport/outliner and use the python console to figure out:
>>> C.object
bpy.data.objects['Cube']
>>> C.object.rotation_mode # get the rotation mode
'XYZ'
>>> C.object.rotation_mode = 'QUATERNION' # set the rotation mode
...
Based on that knowledge, it should be pretty straight forward to adapt the given script:
import bpy
from mathutils import Vector
C = bpy.context
obj = C.object
direction = Vector((1.0, 0.0, 0.0))
obj.rotation_mode = 'QUATERNION'
obj.rotation_quaternion = direction.to_track_quat('Z','Y')
If you'd like to access objects by their name, best practice to get the actual object reference is using pythons get() on Scene.objects collection. Using the index operator [] on Scene.objects collection would raise a KeyError if the key is missing however (object name or index in this case). I'd suggest use the python console to figure out:
>>> C.scene.objects.get("Cube")
bpy.data.objects['Cube'] # object reference
>>> C.scene.objects["Cube1"]
Traceback (most recent call last):
File "<blender_console>", line 1, in <module>
KeyError: 'bpy_prop_collection[key]: key "Cube1" not found'
>>> C.scene.objects.get("Cube1", False) # get allows to provide a default value
False
See: Why dict.get(key) instead of dict[key]?
>>> obj = C.scene.objects.get("Cube")
>>> obj
bpy.data.objects['Cube']
>>> obj.rotation_mode
'XYZ'
Based on that knowledge, it should be pretty straight forward to adapt the given script:
import bpy
from mathutils import Vector
C = bpy.context
obj = C.scene.objects.get("Cube")
if obj:
direction = Vector((1.0,0.0,0.0))
obj.rotation_mode = 'QUATERNION'
obj.rotation_quaternion = direction.to_track_quat('Z','Y')
You can also use get() on the object data-block of the current file D.objects.get("Cube"). However, might lead into potential context issues if eg. the object you're trying to access is no part of the current scene.
Related:
C.objector via sceneC.scene.object.get("Cube"). Suggest use the python console to figure out: https://docs.blender.org/manual/en/latest/editors/python_console.html – brockmann Sep 25 '21 at 13:03bpy.ops.outliner.item_activate(extend=False, deselect_all=True)– Dirk Schiller Sep 25 '21 at 13:06C.scene.object.get("Area.001")and hit enter I get this error:Traceback (most recent call last): File "<blender_console>", line 1, in <module> AttributeError: 'Scene' object has no attribute 'object'– Dirk Schiller Sep 25 '21 at 13:13