- Notifications
You must be signed in to change notification settings - Fork749
Open
Description
When installing editable dependencies with pip or other python package managers into a virtualenv, they end up insite-packages
as.pth
files which contain the actual absolute path of the package.
Usually, python is able to follow these as if they were symlinks and import packages that were installed that way. However, this doesn't seem to work with Python.NET. I just get an error inPy.Import
:
An exception of type 'Python.Runtime.PythonException' occurred in Python.Runtime but was not handled in user code: 'No module named 'mymodule''
I do have a workaround for this, which is just to read all the.pth
files and add those paths to PYTHONPATH manually, but it would be much nicer if this could just work out of the box.
stringvirtualEnvPath=$@".\myDir\.venv";stringvenvSitePackagesPath=$@"{sVirtualEnvPath}\Lib\site-packages";// Resolve editable dependencies manually because Python.NET doesn't do sostring[]editableDependencyReferences=Directory.GetFiles(venvSitePackagesPath,"*.pth");string[]editableDependencyPaths=editableDependencyReferences.Select(filePath=>File.ReadAllText(filePath).Trim()).ToArray();stringpythonPath=$"{venvSitePackagesPath};"+@"C:\Program Files\Python312\Lib;"+@"C:\Program Files\Python312\DLLs;"+string.Join(";",editableDependencyPaths);// Add them to the pathEnvironment.SetEnvironmentVariable("PATH",Environment.GetEnvironmentVariable("PATH").TrimEnd(';')+";"+virtualEnvPath,EnvironmentVariableTarget.Process);Environment.SetEnvironmentVariable("PYTHONHOME",virtualEnvPath,EnvironmentVariableTarget.Process);Environment.SetEnvironmentVariable("PYTHONPATH",pythonPath,EnvironmentVariableTarget.Process);PythonEngine.PythonHome=virtualEnvPath;PythonEngine.PythonPath=pythonPath;PythonEngine.Initialize();using(Py.GIL()){dynamicmymodule=Py.Import("mymodule");// Succeeds now!}
Metadata
Metadata
Assignees
Labels
No labels