# Run a Python script as subprocess from Slicer

**URL:** <https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668>\
**Category:** Support\
**Tags:** python\
**Created:** [March 24, 2022, 12:18pm UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668 "2022-03-24T12:18:09Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![lb123](https://avatars.discourse-cdn.com/v4/letter/l/85e7bf/32.png) [@lb123](https://discourse.slicer.org/u/lb123)\
**Post date:** [March 24, 2022, 12:18pm UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/1 "2022-03-24T12:18:09Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![ebrahim](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/ebrahim/32/13403_2.png) [@ebrahim](https://discourse.slicer.org/u/ebrahim)\
**Post date:** [March 24, 2022, 12:22pm UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/2 "2022-03-24T12:22:34Z")

</div>

Maybe `slicer.util.launchConsoleProcess` could work for this

---

<div class="post-metadata">

**Author:** ![lassoan](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/lassoan/32/13_2.png) [@lassoan](https://discourse.slicer.org/u/lassoan)\
**Post date:** [March 26, 2022, 4:21am UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/3 "2022-03-26T04:21:39Z")

</div>

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](https://github.com/lassoan/SlicerPythonCLIExample)

---

<div class="post-metadata">

**Author:** ![lb123](https://avatars.discourse-cdn.com/v4/letter/l/85e7bf/32.png) [@lb123](https://discourse.slicer.org/u/lb123)\
**Post date:** [March 28, 2022, 7:57am UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/4 "2022-03-28T07:57:57Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![lassoan](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/lassoan/32/13_2.png) [@lassoan](https://discourse.slicer.org/u/lassoan)\
**Post date:** [March 28, 2022, 11:16am UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/5 "2022-03-28T11:16:52Z")

</div>

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

> [@Third party library works slower inside Slicer's Python shell - why? how to do performance profiling?](https://discourse.slicer.org/t/third-party-library-works-slower-inside-slicers-python-shell-why-how-to-do-performance-profiling/18742):
>
> Hi, I’m trying to use python package [lasio](https://github.com/kinverarity1/lasio). It is geological library and its main purpose is to read textual files of format .las After installing it (pip install lasio) I can use it as follows: import lasio las = lasio.read("path/to/las/file") # I provide an example file below The problem is that if I read this .las file (via command las = lasio.read("path/to/las/file")) in Slicer’s python shell then it works noticeably slower (about 5 seconds) than when I open PythonSlicer.exe in Window…

---

<div class="post-metadata">

**Author:** ![lb123](https://avatars.discourse-cdn.com/v4/letter/l/85e7bf/32.png) [@lb123](https://discourse.slicer.org/u/lb123)\
**Post date:** [March 28, 2022, 11:43am UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/6 "2022-03-28T11:43:50Z")

</div>

Thank you.

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

```auto
import os
.
.
.

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

```

but I am getting this error:

```auto
module 'os' has no attribute 'add_dll_directory'

```

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

```auto
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

---

<div class="post-metadata">

**Author:** ![lassoan](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/lassoan/32/13_2.png) [@lassoan](https://discourse.slicer.org/u/lassoan)\
**Post date:** [March 28, 2022, 12:13pm UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/7 "2022-03-28T12:13:31Z")

</div>

`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](https://slicer.readthedocs.io/en/latest/developer_guide/script_repository.html#launch-external-process-in-startup-environment).

There is also the [`slicer.util.launchConsoleProcess`](https://slicer.readthedocs.io/en/latest/developer_guide/slicer.html#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](https://slicer.readthedocs.io/en/latest/developer_guide/slicer.html#slicer.util.logProcessOutput) 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](https://github.com/Slicer/Slicer/blob/b362a139d35373c6cccfff501c3935c482c52024/Base/Python/slicer/util.py#L3287-L3307).

---

<div class="post-metadata">

**Author:** ![Saima](https://avatars.discourse-cdn.com/v4/letter/s/9d8465/32.png) [@Saima](https://discourse.slicer.org/u/Saima)\
**Post date:** [February 6, 2023, 4:42am UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/8 "2023-02-06T04:42:31Z")

</div>

Hi Andras,  
I have created a slicerpythonscriptedcli module. Is it possible to call subprocess\_check\_out to run a program using anaconda.

I am using some libraries that are installed in an enviornment in anaconda thats why I am calling the external python to run a program.

Please let me know how can i do it.

I receive the following error:

Traceback (most recent call last):  
File “/home/useradmin/Slicer-4.11.20210226-linux-amd64/Scheduler/scheduler/scheduler.py”, line 68, in  
main(sys.argv[1], float(sys.argv[2]), sys.argv[3], sys.argv[4], sys.argv[5])  
File “/home/useradmin/Slicer-4.11.20210226-linux-amd64/Scheduler/scheduler/scheduler.py”, line 50, in main  
command\_result = check\_output(command\_line, env=slicer.util.startupEnvironment())  
File “/home/useradmin/Slicer-4.11.20210226-linux-amd64/bin/Python/slicer/util.py”, line 106, in startupEnvironment  
startupEnv = slicer.app.startupEnvironment()  
AttributeError: module ‘slicer’ has no attribute ‘app’

regards,  
Saima

---

<div class="post-metadata">

**Author:** ![lassoan](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/lassoan/32/13_2.png) [@lassoan](https://discourse.slicer.org/u/lassoan)\
**Post date:** [February 6, 2023, 4:34pm UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/9 "2023-02-06T16:34:40Z")

</div>

`slicer.util.startupEnvironment()` requires that you run the script using `./Slicer` executable (and not using `./PythonSlicer` executable).

You could get the startup environment by calling the `ctkAppLauncherEnvironment::environment(0)` method in C++, but the only Python-wrapped class that exposes this method is qSlicerCoreApplication. If you start your Python script using `./PythonSlicer` then no Qt application class is created, so you would need to add a new C++ class that allows you to call this function.

> [@Saima](#):
>
> I am using some libraries that are installed in an enviornment in anaconda thats why I am calling the external python to run a program.

It would be much simpler to install the libraries using PyPI into Slicer’s Python environment. What are these libraries?

---

<div class="post-metadata">

**Author:** ![Saima](https://avatars.discourse-cdn.com/v4/letter/s/9d8465/32.png) [@Saima](https://discourse.slicer.org/u/Saima)\
**Post date:** [February 7, 2023, 2:23am UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/10 "2023-02-07T02:23:35Z")

</div>

Its a toolkit, bratstoolkit for tumour segmentation.

regards,  
Saima

---

<div class="post-metadata">

**Author:** ![Saima](https://avatars.discourse-cdn.com/v4/letter/s/9d8465/32.png) [@Saima](https://discourse.slicer.org/u/Saima)\
**Post date:** [February 7, 2023, 2:30am UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/11 "2023-02-07T02:30:33Z")

</div>

Hi andras,  
can I run check\_output or run without env variable and run the process outside the slicer in an anaconda enviornment and get the results and avoid running into error due to startupenviornment.

At this stage I have to not use anything from slicer but after the processing the output is a volume(.nrrd), which I will export and do some processing on it.

regards,  
Saima Safdar

---

<div class="post-metadata">

**Author:** ![lassoan](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.slicer.org/lassoan/32/13_2.png) [@lassoan](https://discourse.slicer.org/u/lassoan)\
**Post date:** [February 7, 2023, 1:58pm UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/12 "2023-02-07T13:58:50Z")

</div>

> [@Saima](#):
>
> Its a toolkit, bratstoolkit for tumour segmentation.

You can pip install it in Slicer’s Python environment (`PythonSlicer.exe -m pip install BraTS-Toolkit`). There should be no need to mess with anaconda.

There is a problem that this package pins a very specific version of SimpleITK (and a couple of other Python packages), which makes Slicer remove the special SimpleITK distribution that is bundled with Slicer, so modules that rely on SimpleITK may stop working. See [Did sitkUtils.PullVolumeFromSlicer() break with Slicer 5.2? - #9 by lassoan](https://discourse.slicer.org/t/did-sitkutils-pullvolumefromslicer-break-with-slicer-5-2/26863/9) for more details.

Another bad thing about this [bratstoolkit](https://github.com/neuronflow/BraTS-Toolkit) is that it comes with the strictest possible copyleft license. If you use this code then you must make all other code in the same project public. Probably you can find other segmentation toolkits that provide similar features and do not come with such heavy restrictions.

---

<div class="post-metadata">

**Author:** ![Saima](https://avatars.discourse-cdn.com/v4/letter/s/9d8465/32.png) [@Saima](https://discourse.slicer.org/u/Saima)\
**Post date:** [February 8, 2023, 3:13am UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/13 "2023-02-08T03:13:02Z")

</div>

Hi Andras,  
For the bratstoolkit, may be I could run it outside the slicer and get the results back into the slicer using the subprocess command and make the scripted module.

Is this ok? because if i dont install within slicer I will not have the SimpleITK issue.  
The only thing I need for scripted module is how cani display the output or errors like in the  
pythonCLi based module. That is a desperate post.

Can you suggest some other tumour segmentation toolkits ?

regards,  
Saima

---

<div class="post-metadata">

**Author:** ![Saima](https://avatars.discourse-cdn.com/v4/letter/s/9d8465/32.png) [@Saima](https://discourse.slicer.org/u/Saima)\
**Post date:** [May 6, 2024, 7:59am UTC](https://discourse.slicer.org/t/run-a-python-script-as-subprocess-from-slicer/22668/14 "2024-05-06T07:59:34Z")

</div>

Hi Andras,  
I have submitted the batchBrainMRSegmentation extension. The suggestion is to make CLI modules for each of the files I am calling through the main scripted python module.

I started making the cli module. It did install the bratstoolkit but I am getting this error now. Please see below. How can I proceed further. Please help.

Error response from daemon: No such container: greedy\_elephant  
Error: No such container: greedy\_elephant  
Error response from daemon: No such container: greedy\_elephant  
docker: Error response from daemon: could not select device driver “” with capabilities: [[gpu]].  
Error: No such container: greedy\_elephant  
Error: No such container: greedy\_elephant  
Error: No such container: greedy\_elephant  
Error: No such container: greedy\_elephant  
Traceback (most recent call last):  
File “/media/useradmin/Disk2/Slicer-5.7.0-2024-03-25-linux-amd64(1)/Slicer-5.7.0-2024-03-25-linux-amd64/lib/Python/lib/python3.9/site-packages/socketio/client.py”, line 280, in connect  
self.eio.connect(url, headers=headers, transports=transports,  
File “/media/useradmin/Disk2/Slicer-5.7.0-2024-03-25-linux-amd64(1)/Slicer-5.7.0-2024-03-25-linux-amd64/lib/Python/lib/python3.9/site-packages/engineio/client.py”, line 194, in connect  
return getattr(self, ‘_connect_’ + self.transports[0])(  
File “/media/useradmin/Disk2/Slicer-5.7.0-2024-03-25-linux-amd64(1)/Slicer-5.7.0-2024-03-25-linux-amd64/lib/Python/lib/python3.9/site-packages/engineio/client.py”, line 300, in \_connect\_polling  
raise exceptions.ConnectionError(  
engineio.exceptions.ConnectionError: Connection refused by the server

During handling of the above exception, another exception occurred:

Traceback (most recent call last):  
File “/media/useradmin/Disk2/Slicer-5.7.0-2024-03-25-linux-amd64(1)/Slicer-5.7.0-2024-03-25-linux-amd64/SlicerBratsPreprocessor/BratsPreprocessor/BratsPreprocessor.py”, line 79, in   
main(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7])  
File “/media/useradmin/Disk2/Slicer-5.7.0-2024-03-25-linux-amd64(1)/Slicer-5.7.0-2024-03-25-linux-amd64/SlicerBratsPreprocessor/BratsPreprocessor/BratsPreprocessor.py”, line 60, in main  
prep.single\_preprocess(t1File=t1File, t1cFile=t1cFile, t2File=t2File, flaFile=flaFile, outputFolder=outputDir, mode=“gpu”, confirm=True, skipUpdate=False, gpuid=‘0’)  
File “/media/useradmin/Disk2/Slicer-5.7.0-2024-03-25-linux-amd64(1)/Slicer-5.7.0-2024-03-25-linux-amd64/lib/Python/lib/python3.9/site-packages/brats\_toolkit/preprocessor.py”, line 127, in single\_preprocess  
self.batch\_preprocess(  
File “/media/useradmin/Disk2/Slicer-5.7.0-2024-03-25-linux-amd64(1)/Slicer-5.7.0-2024-03-25-linux-amd64/lib/Python/lib/python3.9/site-packages/brats\_toolkit/preprocessor.py”, line 168, in batch\_preprocess  
self.\_connect\_client()  
File “/media/useradmin/Disk2/Slicer-5.7.0-2024-03-25-linux-amd64(1)/Slicer-5.7.0-2024-03-25-linux-amd64/lib/Python/lib/python3.9/site-packages/brats\_toolkit/preprocessor.py”, line 172, in \_connect\_client  
self.sio.connect(“[http://localhost:5000](http://localhost:5000)”)  
File “/media/useradmin/Disk2/Slicer-5.7.0-2024-03-25-linux-amd64(1)/Slicer-5.7.0-2024-03-25-linux-amd64/lib/Python/lib/python3.9/site-packages/socketio/client.py”, line 283, in connect  
self.\_trigger\_event(  
File “/media/useradmin/Disk2/Slicer-5.7.0-2024-03-25-linux-amd64(1)/Slicer-5.7.0-2024-03-25-linux-amd64/lib/Python/lib/python3.9/site-packages/socketio/client.py”, line 555, in \_trigger\_event  
return self.handlers[namespace]event  
TypeError: connect\_error() takes 0 positional arguments but 1 was given
