use of external pip libraries in Python plugins

pip is not included in the appimage with the current version (5.2.6); therefore the solution provided in the original post fails with an error.

However, I had more success installing the packages (or, indeed, pip itself) from a terminal provided I used the right version of Python and the right location.

Packages can be installed (almost painlessly, or perhaps a little painfully) as follows:

  1. Install pyenv - follow their instructions.
  2. Check the version and path of Python used by Krita via Scripter with:
    import sys
    print(sys.version)
    # 3.10.7 (main, Sep 25 2024, 09:46:00) [GCC 11.4.0]
    print(sys.path)
    # [ '/tmp/.mount_krita-p9vswE/usr/lib/krita-python-libs/krita',
    #   '/home/username/.local/share/krita/pykrita' ... ]
    
    The comments are snippets of the output from my Ubuntu MATE machine with Krita 5.2.6 appimage.
  3. Open a terminal select the version using pyenv:
    pyenv install 3.10
    pyenv shell 3.10
    
  4. Install the package to one of the (user) folders in sys.path, e.g.
    pip install numpy --target=/home/username/.local/share/krita/pykrita`
    

From Scripter, I can then import no problem:

import numpy
print(numpy.__file__)
# /home/username/.local/share/krita/pykrita/numpy/__init__.py

It’s plausible that a similar approach will work on Windows - the main hassle will be getting used to pyenv.

Bonus: You can also install pip to the same location as demonstrated for numpy above, and then similarly to the original post (but with less pretty wrapping) I can run the following in Scripter to install pillow:

import sys
import runpy

def exitFct(exitCode):
    return exitCode

sys_exit_old = sys.exit
sys_argv_old = sys.argv
sys.exit = exitFct

try:
    sys.argv.append('install')
    sys.argv.append('pillow')
    sys.argv.append('--target=/home/username/.local/share/krita/pykrita')
    runpy.run_module('pip', run_name='__main__')
except Exception as e:
    print(f'{e}')

sys.exit = sys_exit_old
sys.argv = sys_argv_old

I get a tonne of errors related to logging, but it succeeds.