Automate "Rotate slice to volume plane" feature in Python

Is there anyway to automate rotating a slice window? (I.e. automate the clicking of the “rotate to volume plane” button)

I have tried:

controller = slicer.qMRMLSliceControllerWidget()
controller.rotateSliceToBackground()

but this doesn’t seem to do anything, and I don’t know how to associate this with a particular slice window (i.e. a particular qMRMLSliceWidget)

Examples in the script repository should help: https://www.slicer.org/wiki/Documentation/Nightly/ScriptRepository#Manipulate_a_Slice_View

That will just create an instance of a new controller widget but you want the ones that are associated with views in the layout, like this from the examples @lassoan linked:

for sliceViewName in layoutManager.sliceViewNames():
     sliceWidget = layoutManager.sliceWidget(sliceViewName)
     
     controller = sliceWidget.sliceController()