Open
Description
When installing editable dependencies with pip or other python package managers into a virtualenv, they end up in site-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 in Py.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.
string virtualEnvPath = $@".\myDir\.venv";
string venvSitePackagesPath = $@"{sVirtualEnvPath}\Lib\site-packages";
// Resolve editable dependencies manually because Python.NET doesn't do so
string[] editableDependencyReferences = Directory.GetFiles(venvSitePackagesPath, "*.pth");
string[] editableDependencyPaths = editableDependencyReferences
.Select(filePath => File.ReadAllText(filePath).Trim())
.ToArray();
string pythonPath = $"{venvSitePackagesPath};" +
@"C:\Program Files\Python312\Lib;" +
@"C:\Program Files\Python312\DLLs;" +
string.Join(";", editableDependencyPaths); // Add them to the path
Environment.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())
{
dynamic mymodule = Py.Import("mymodule"); // Succeeds now!
}
Metadata
Metadata
Assignees
Labels
No labels