changeset 1018:868552e0caf8

python venv
author Alain Mazy <am@osimis.io>
date Thu, 25 Jan 2024 11:33:50 +0100
parents 3f3a1b54a839
children a1d28570ef23
files Sphinx/source/plugins/python.rst Sphinx/source/plugins/python/venv-linux.py Sphinx/source/plugins/python/venv-windows.py
diffstat 3 files changed, 51 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/Sphinx/source/plugins/python.rst	Fri Jan 19 16:57:13 2024 +0100
+++ b/Sphinx/source/plugins/python.rst	Thu Jan 25 11:33:50 2024 +0100
@@ -1011,3 +1011,32 @@
 
 .. literalinclude:: python/multiprocessing-4.py
                     :language: python
+
+Working with virtual environments
+---------------------------------
+
+By default, Orthanc uses the system-wide Python installation and
+therefore has access to the python modules that have been installed
+system-wide.
+
+As of version 4.1 of the python plugin, there is no built-in support
+for working with a `virtual environment <https://docs.python.org/3/library/venv.html>`__.
+However, you may modify the python path at the very beginning of the script
+to instruct python to look for modules in your environment.
+
+**Example 1**: On a Linux system, consider that you have created a virtual environment in ``/tmp/.venv``
+and you want to use only the modules that have been installed in this virtual environment.
+In this case, you may simply rewrite ``sys.path``:
+
+.. literalinclude:: python/venv-linux.py
+                    :language: python
+
+
+**Example 2**: On a Windows system, consider that you have created a virtual environment in ``C:/tmp/.venv/``.
+Instead of defining ``sys.path`` from scratch, it is possible to simply insert the venv-packages in
+the ``sys.path``.  By adding the ``venv`` to an early index (``0``), any package required by your code 
+will be looked up in the ``venv`` first.  And, as a consequence, if the package is not present, the system-wide 
+installation of that package might be loaded:
+
+.. literalinclude:: python/venv-windows.py
+                    :language: python
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Sphinx/source/plugins/python/venv-linux.py	Thu Jan 25 11:33:50 2024 +0100
@@ -0,0 +1,11 @@
+import orthanc
+import sys
+
+print("sys.path before modification: " + ", ".join(sys.path))
+
+sys.path = ["/usr/lib/python3.8", "/usr/lib/python3.8/lib-dynload", "/tmp/.env/lib/python3.8/site-packages", "/tmp/.venv/lib64/python3.8/site-packages"]
+
+print("sys.path after modification: " + ", ".join(sys.path))
+
+import requests
+# ....
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Sphinx/source/plugins/python/venv-windows.py	Thu Jan 25 11:33:50 2024 +0100
@@ -0,0 +1,11 @@
+import orthanc
+import sys
+
+print("sys.path before modification: " + ", ".join(sys.path))
+
+sys.path.insert(0, "C:/tmp/.venv/Lib/site-packages")
+
+print("sys.path after modification: " + ", ".join(sys.path))
+
+import requests
+# ....