I am using Orthanc on a VM that runs Windows Server 2016 with addition of the Python plugin (3.10) to add my own callbacks. Since the VM is not only dedicated to Orthanc, I want to encapsulate Orthanc and all of my Python code as much as possibe, which brings up the idea of a venv.
I am by no means an experienced developer so I tried the naive approach of compiling the plugin from source to be able to link it against the python.exe of my venv instead of the system wide Python installation. However, the build process failed with the error message saying that it is not able to find the python.h header files.
Did anyone figure out how to use the Python plugin in combination with a venv or is that even possible?
There is currently nothing foreseen for selecting a virtual env in the plugin.
However, I just made a few tests on my Linux machine where I modify the sys.path at the very beginning of the python script, before loading other non-system modules. (note: I have created a virtual env in /tmp/.env/ :
I tested this using your example of whether requests is present in the venv when starting up Orthanc with my Python code.
Alternative: Instead of defining sys.path from scratch, it’s possible to insert the venv-packages like this (note: The venv is in the same directory as my executed Python file):
By adding the venv to an early index (0), any package required by my code will be looked up in the venv first. However, as a consequence, if the package is not present, the system-wide installation of that package might be chosen. This is something to be mindful of.
Using a Virtual Environment (venv) in that way is not exactly encouraged but probably sufficient for my use case.
There’s no issue on altering sys.path, and no need to trim it down.
An additional way to achieve the same is setting PYTHONPATH in the env of the Orthanc process, this will be looked for and used by libpython interpreter init.
The output with a print(f"DEBUG: {sys.path=}") is:
Thanks for that. I have included it as well in the orthanc-book and provided a sample for Docker containers:
FROM orthancteam/orthanc-pre-release:bookworm
# This example is using a virtual env that is not mandatory when using Docker containers
# but recommended since python 3.11 and Debian bookworm based images where you get a warning
# when installing system-wide packages.
RUN apt-get update && apt install -y python3-venv
RUN python3 -m venv /.venv
RUN /.venv/bin/pip install pydicom
ENV PYTHONPATH=/.venv/lib64/python3.11/site-packages/
...
My bad, my example was meant to just show how to inject a path into sys.path.
I see how the choice of /tmp/venv was misleading.
I think activating the environment before starting Orthanc in a batch file is not going to work as the interpreter is being inited by Orthanc and the activation script is not setting PYTHONPATH in env, but I am not sure about it.