这是我的代码
Runtime.PythonDLL = @"D:\Dev\Console\.conda\python311.dll";
PythonEngine.Initialize();
dynamic sys = Py.Import("sys");
Console.WriteLine("Python version: " + sys.version);
.conda 是我使用 VSCode 创建的虚拟环境。
我收到此错误消息。
System.TypeInitializationException:'类型初始值设定项 “代表们”抛出了一个例外。 DllNotFoundException:无法加载 D:\Dev\Console.conda\python311.dll。 Win32Exception:指定的 找不到模块。
谢谢。
这里是我如何将虚拟Python环境嵌入到.net中
string pathToVirtualEnv = "";
if (Debugger.IsAttached)
{
pathToVirtualEnv = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.Parent.FullName + @"\.conda\";
}
else
{
//TODO: Define your virtual env path here
throw new NotImplementedException();
}
// be sure not to overwrite your existing "PATH" environmental variable.
var path = Environment.GetEnvironmentVariable("PATH").TrimEnd(';');
path = string.IsNullOrEmpty(path) ? pathToVirtualEnv : path + ";" + pathToVirtualEnv;
var process = EnvironmentVariableTarget.Process;
Environment.SetEnvironmentVariable("PATH", path, process);
Environment.SetEnvironmentVariable("PATH", pathToVirtualEnv, process);
Environment.SetEnvironmentVariable("PYTHONHOME", pathToVirtualEnv, process);
Environment.SetEnvironmentVariable("PYTHONPATH", $"{pathToVirtualEnv}\\Lib\\site-packages;{pathToVirtualEnv}\\Lib", process);
Runtime.PythonDLL = pathToVirtualEnv + @"python311.dll";
PythonEngine.PythonHome = pathToVirtualEnv;
PythonEngine.PythonPath = Environment.GetEnvironmentVariable("PYTHONPATH", EnvironmentVariableTarget.Process);
PythonEngine.Initialize();
dynamic sys = Py.Import("sys");
Console.WriteLine("Python version: " + sys.version);