skip to Main Content

In my python-based project I am using several functions from PySide6. These functions require libraries such as libGl.so and libglib.so. This is not a problem when using the package as a standalone-package.

When packaging it into a docker-image and using python:3.12 or similar base images, I however have to add

RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 libegl-dev -y

during build-time, to add these packages. As I try to keep my resulting image as small as possible, I would like to avoid this step.

Is there any way of using something similar as (e.g.) preprocessor routines in C++, to selectively disable imports depending on availability of libraries? I am aware of that this might also disable other functions, but for the purpose of this question this is not relevant, as I don’t use these functions anyway in the volume-context.

2

Answers


  1. You could use following structure, to import only available packages:

    try:
        import some_module
    except ImportError:
        some_module = None
    
    if some_module:
        pass
    else:
        pass
    
    Login or Signup to reply.
  2. you can conditionally import modules based on the availability of external libraries by using a try-except block

    try:
        from PySide6 import <your_library>
    except ImportError:
        pass
    

    This way, the import will only happen if the required libraries are available

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search