Inconsistent handling of multiprocessing by slicer

On a Windows 10 enterprise computer the following multiprocessing code block evaluates differently for two execution commands. Executing the script directly with PythonSlicer.exe gives the expected result, i.e., output is reported for both main and fun. However, executing the script with slicer.exe --python-script [script] only reports output from main, suggesting that fun has not been called, thereby implying a problem with the multiprocessing. In contrast, on a Mac, both execution approaches (either using python directly, or piping through slicer) return output from both main and fun.

I mostly want to execute the python script using slicer.exe to access the ctk and slicer modules, which I don’t believe I can access from the PythonSlicer.exe python bundle. Any suggestions are much appreciated.

import sys
import time
from multiprocessing import Process

def fun():

    outfile = open('test_fun.log','w')
    print("Starting fun")
    outfile.write('Starting fun\n')
    time.sleep(2)
    outfile.write('Finishing fun')
    print('Finishing fun')
    outfile.close()

def main():

    p = Process(target=fun)
    p.start()
    p.join()

if __name__ == '__main__':

    print('Starting main')
    outfile = open('test_main.log', 'w')
    main()
    outfile.write('Yes in main()')
    outfile.close()
    print('Finishing main')
    sys.exit(0)

There could definitely be differences between --python-script, which happens in the slicer application main loop, and running in the PythonSlicer interpreter with regards to multiprocessing. In the context of the Slicer main loop you might have more luck with QProcess like we use in the SlicerParallelProcessing extension.

1 Like

Thanks I will check it out.