Run a Python script as subprocess from Slicer

Hi,
can you please tell me how I can run a python script as a subprocess from Slicer?
I would like to lauch a python file from the logic of my module.

Thank you

Maybe slicer.util.launchConsoleProcess could work for this

You can also run your Python script as a CLI module. Slicer automatically generates a GUI for specifying inputs and outputs; and you can also run the script as any other CLI module. See a complete example here: GitHub - lassoan/SlicerPythonCLIExample: Example extension for 3D Slicer that demonstrates how to make a Python script available as a CLI module

1 Like

Thank you for your reply.

I noticed that the python script runned as a CLI module is much slower than if I run it from an external command prompt.

Do you know any possible reason?

Thank you

You can get definitive answer by using a Python profiler, but a likely root cause is excessive logging. See more details here:

Thank you.

I also tried to run a simple os.system from the logic of my Slicer module:

import os
.
.
.

path_to_python = "python_path//"
os.system(f"{path_to_python}python.exe myscript.py")

but I am getting this error:

module 'os' has no attribute 'add_dll_directory'

While if I do the same from a Windows command prompt it works well:

import os
path_to_python = "python_path//"
os.system(f"{path_to_python}python.exe myscript.py")

Do you know the reason for this behaviour?

Thank you

os.system is a very rudimentary tool, you cannot control the used environment, output redirections, ownership of thr process, etc. Use subprocess instead. Set example here.

There is also the slicer.util.launchConsoleProcess function that conveniently redirects outputs, sets the environment, hides the console, gives access to the process so that you can log its outputs or if user requests then terminate the process.

If you want to run Python then you can use Slicer’s Python environment as shown here.