linuxpythonraspbiandebian-buster

How to find the location of a specific "include" library in Python?


Within a particular Python program, how do I know what and where a particular included file is?

For example: given import EASY from easygopigo, how do I find which one of many easygopigo libraries are being used?

In other words, I'd like the Python equivalent of which [command] as in "which [library file]", that would give me the path and filename of the file that would be used when I include it.

Specifically, I have a robot running Raspberry Pi O/S Buster with Python 3.7 installed. Many of the robot's programming interfaces are Python files that include various libraries. For example, two libraries are universally used: easygopigo and gopigo.

For whatever reason, there seem to be six or seven copies of these files scattered around, some in the "pi" user's home directory and/or subdirectories, others in various other places within the filesystem.

The operating system version and the version of Python installed, (etc.), are hard requirements and cannot be changed without a non-trivial effort which isn't going to happen (there are ongoing efforts to update the gopigo libraries to run on Bullseye and Bookworm, but these are long-term projects that won't help me here as they're not even close to completion).


Solution

  • after it has been imported, callstr() on it, or (for many/most modules) look at the .__path__ attribute of the module.

    >>> import numpy
    >>> print(str(numpy))
    <module 'numpy' from '/Library/Frameworks/Python.framework/Versions/3.12/...numpy/__init__.py'
    >>> numpy.__path__
    ['/Library/Frameworks/Python.framework/Versions/3.12/.../site-packages/numpy']
    

    To determine before it is actually imported, you need to search through sys.path