Caleb Marcum
Caleb Marcum

Reputation: 31

Importing .pyd is failing if the path to the module is added at runtime (Python 3.8)

Overview

I have a python script in a PyCharm project which requires the use of foo.pyd (import foo). When looking this problem up, I've found 2 solutions.

Attempted Solutions

The PYTHONPATH environment variable

  1. Add the path to the module(s) to PYTHONPATH before the script executes. This will add the paths within the PYTHONPATH variable to the sys.path list, and will allow python to search all those known paths for modules when importing.
import os
os.environ['PYTHONPATH'] += 'C:\\path\\to\\module' + os.pathsep
import foo

ModuleNotFoundError: No module named 'foo'
I believe this to indicate the import didn't find the module as python never found a path that contained foo.py, foo.pyc, or foo.pyd, thus "Module Not Found".

The sys.path variable

  1. Add the path to the module(s) to the sys.path list directly, since the paths from PYTHONPATH get added here for python to search. This will allow python to check the known paths for modules when importing.
import sys
sys.path.append('C:\\path\\to\\module')
import foo

ImportError: DLL load failed while importing foo: The specified module could not be found.
I believe this indicates that python at least made some progress since this is a different error. However, the error still reads the same, as if it didn't find the foo module at all. However, now it specifies a missing dll. So perhaps, this means there is a problem with a dependency of foo.pyd? But if that were the case, the following wouldn't work...

Only Success so Far

The only way I've managed to successfully import foo.pyd, is by ensuring its folder path is added to PYTHONPATH before running the script. In PyCharm, I've done this by adding that path to the "Interpreter's Paths". This actually works, and imports foo as expected. However, I don't understand why this works, but I can't seem to add the path at runtime as so many others appear to be able to do.

Upvotes: 1

Views: 75

Answers (0)

Related Questions