How to define and save output of a cli module in Python script?

Hi,
I’m trying to run N4ITK Bias correction (a cli module) from Jupyter Notebook and am struggling with defining the output parameter.
The code I wrote reads my inputs and creates a node, but I don’t know whether it ran (executed the bias correction) and how to save the output. I am working with NIFTII images.
My code:

input_volume=slicer.util.loadVolume(path_to_T1)
slicernb.ViewDisplay()#it worked
mask_volume=slicer.util.loadVolume(path_to_mask)
slicernb.ViewDisplay()#it worked
output_volume=(slicer.mrmlScene.AddNewNodeByClass (“vtkMRMLCommandLineModuleNode”,“Name_for_corrected volume.nii”))

slicer.mrmlScene.AddNode(output_volume)

parameters={}
parameters[‘initialMeshResolution’]=(1,1,1)
parameters[‘splineDistance’]=0.00
parameters[‘bfFWHM’]=0.00
parameters[‘numberOfIterations’]=(200,200,200)
parameters[‘convergenceThreshold’]=0.0001
parameters[‘bsplineOrder’]=3
parameters[‘shrinkFactor’]=4
parameters[‘weightImageName’]=‘None’
parameters[‘wienerFilterNoise’]=0.00
parameters[‘nHistogramBins’]=0
parameters[‘inputImageName’]=input_volume.GetID()
parameters[‘maskImageName’]=mask_volume.GetID()
parameters[‘outputImageName’]=output_volume.GetID()
parameters[‘outputBiasFieldName’]=‘None’

slicer.cli.run(slicer.modules.n4itkbiasfieldcorrection,node=None,parameters=parameters)

How could I make it save a corrected T1 volume?

You probably want slicer.cli.runSync

See https://www.slicer.org/wiki/Documentation/Nightly/Developers/Python_scripting#Running_a_CLI_from_Python

This issues comes up so often that I think we should change the default behavior of run to be runSync. It would be a good opportunity to do it now (for Slicer5). What do you think? @pieper @cpinter @jcfr

Yes, that makes sense - people expect a python api to by synchronous by default. Rather than a runAsync how about .a method called start to be more explicit what it does.

Thank you for the reply.

I tried to run the code replacing slicer.cli.run by slicer.cli.runSync and now the Jupyter cell is just running for very long, still with no outputs whatsoever.

It would be useful to know what is happening so i tried add these commands (after restarting the kernel):

newNode=slicer.cli.runSync(slicer.modules.n4itkbiasfieldcorrection,
node=None,parameters=parameters)
newNode.GetOutputText()
newNode.GetErrorText()

but with no messages displayed - it seems that the execution is somehow stuck at slicer.cli.runSync() for some reason.

Is there something wrong with my code?

Can you provide the complete script (using one of the Slicer sample data sets as input)?