Install python library with extension

Hi all,
the extension I’m developing needs an external python library.
I can install it by using pip_install in the python shell but, of course I need to embed this into the installation process.
How can I do this?
Thanks a lot.

Paolo

Hi Paolo,

You can use the following structure to do this right in the module. The first time the module is loaded the library will be automatically installed, and every successive time the import in the try block will succeed and the catch will not be executed.

try:
    import library_name
except:
    slicer.util.pip_install('library_name')
    import library_name

Of course you can use other forms of the Python import lines as well, like
from library_name import module_name

Thanks @markasselin!
Yes, this is a possible solution, but I was looking for a way to do this in the real installation step (maybe you install the extension and the first time you run the extension you have no internet access).

Thanks again

Hi Paulo -

Since the user needs internet to download the extension you are probably safe with the approach Mark suggested. If you want to be one step safer, you could include that code in a method called by when the startupCompleted signal is triggered. If you set this up in the module class it will be triggered every time Slicer starts up with your extension installed. Since they need to restart after installing the extension it’s pretty likely to happen while they are on the internet.

Something like this:

The installation steps that @markasselin and @pieper described are correct.

You cannot install required Python packages during extension installation time, because extensions are shared between all Slicer instances of a specific version, while extension packages are not shared (but installed separately for each Slicer instance).

Tagging for when I forget how to do this.

Thanks a lot!
I used the strategy proposed by @markasselin, it is much more confortable!

Thanks again!
Paolo

Ciao @PaoloZaffino, if your extension is in the extension manager, you can actually do it directly in the cmake (so they will be packed at compilation time on the kitware factory machines):

  1. add python requirements in the superbuild:
    https://github.com/Punzo/SlicerAstro/blob/master/SuperBuild.cmake#L28
    https://github.com/Punzo/SlicerAstro/blob/master/SuperBuild/slicerastro-requirements.txt
    https://github.com/Punzo/SlicerAstro/blob/master/SuperBuild/External_python-slicerastro-requirements.cmake

  2. ensure the packing directly in Slicer build:
    https://github.com/Punzo/SlicerAstro/blob/master/CMakeLists.txt#L169-L176

    (this will not pollute the Slicer build. They will be installed only when you install the extension)

I tested this recently and it works. However, I tested only on linux.

P.S.: If you don’t have a SuperBuild, I advise to add it if you want to use this approach.

1 Like