python script in slicer environment

I’m running a python script using PythonSlicer myscript.py. Here is my script:

import slicer

directory = "/path/to/files"

loadedVolumeNode = slicer.util.loadVolume(directory, {"singleFile": False})

I got this error message:

No module named 'logic'
Traceback (most recent call last):
  File "/path/to/myscript.py", line 9, in <module>
    loadedVolumeNode = slicer.util.loadVolume(directory, {"singleFile": False})
AttributeError: module 'slicer' has no attribute 'util'

Based on slicer documentation, slicer has a module named util. Why it can’t find it?

My slicer version is: Slicer 5.6.2.

Could you please help with this issue? thanks in advance.

PythonSlicer application does not start the Slicer application and so no Slicer modules are instantiated. You may be able to instantiate module logic classes manually and use them, but it is simpler to run your script in the Slicer application’s Python environment

Slicer --no-main-window --python-script "path/to/myfile.py"

Thank you for your reply. I’m trying to run an app which uses slicer’s modules in the back end for visualization without using slicer’s user interface. Is it possible to install Slicer modules as a python package so I can import them in my environment?

We are working on making Slicer core available as pip-installable packages, but it is a long-term project (we need to get funding for it and then work on it for a few years).

But there are several almost as good solutions that you can use until then. The easiest method is to prevent any GUI from appearing is to used dockerized versions of Slicer. But you can also launch Slicer once and hide its window. While Slicer is running, you can use Slicer’s web API to run any commands (e.g., from a web app or from the command line) or you can conveniently use the slicerio Python package to launch Slicer from Python and run commands in Slicer from any Python environment.

Thank you so much for your guidance. I used :

Slicer.exe --python-script "C:/Users/myscript.py"

I run it through subprocess module from my main app and it worked !!

Thanks again, your replies helped me a lot.

Best regards.