- Notifications
You must be signed in to change notification settings - Fork748
Using Python.NET with Virtual Environments
This is a simple tutorial on how to use Python.NET with virtual environments, created viaVirtualenv,Virtualenvwrapper orAnaconda.Common errors indicating there being an issue with your virtual environment configuration include unable to import modules and external DLLs such as
Fatal Python error: initfsencoding: unable to load the file system codecModuleNotFoundError: No module named 'encodings'
and unable to load PythonXXX.dll or Could not load dynamic library 'cublas64_11.dll'; dlerror: cublas64_11.dll not found.
To use your virtual environment, you must configure the environment variablesPATH
,PYTHONHOME
andPYTHONPATH
to point to your virtual environment and not to any other python sources. This should be donebefore setting the python path on thePythonEngine
. ThePATH
environmental variable needs to but updated to include the path to your virtual environment and thePYTHONHOME
variable just needs to point to your virtual environment.
varpathToVirtualEnv=@"path\to\env";varpath=Environment.GetEnvironmentVariable("PATH").TrimEnd(';');path=string.IsNullOrEmpty(path)?pathToVirtualEnv:path+";"+pathToVirtualEnv;Environment.SetEnvironmentVariable("PATH",path,EnvironmentVariableTarget.Process);Environment.SetEnvironmentVariable("PYTHONHOME",pathToVirtualEnv,EnvironmentVariableTarget.Process);
howeverPYTHONPATH
needs to point to theLib
sub-directory as well as theLib\site-packages
sub-directory.
Environment.SetEnvironmentVariable("PYTHONPATH",$"{pathToVirtualEnv}\\Lib\\site-packages;{pathToVirtualEnv}\\Lib",EnvironmentVariableTarget.Process);
Once the environment variables have been setup, you can update thePythonHome
and thePythonPath
on thePythonEngine
.
PythonEngine.PythonHome=pathToVirtualEnv;PythonEngine.PythonPath=Environment.GetEnvironmentVariable("PYTHONPATH",EnvironmentVariableTarget.Process);
Here is an example project demonsrtating the necessary configuration.
usingSystem;usingPython.Runtime;namespaceVirtualenv.Example{publicclassProgram{publicvoidMain(){varpathToVirtualEnv=@"path\to\env";// be sure not to overwrite your existing "PATH" environmental variable.varpath=Environment.GetEnvironmentVariable("PATH").TrimEnd(';');path=string.IsNullOrEmpty(path)?pathToVirtualEnv:path+";"+pathToVirtualEnv;Environment.SetEnvironmentVariable("PATH",path,EnvironmentVariableTarget.Process);Environment.SetEnvironmentVariable("PATH",pathToVirtualEnv,EnvironmentVariableTarget.Process);Environment.SetEnvironmentVariable("PYTHONHOME",pathToVirtualEnv,EnvironmentVariableTarget.Process);Environment.SetEnvironmentVariable("PYTHONPATH",$"{pathToVirtualEnv}\\Lib\\site-packages;{pathToVirtualEnv}\\Lib",EnvironmentVariableTarget.Process);PythonEngine.PythonHome=pathToVirtualEnv;PythonEngine.PythonPath=Environment.GetEnvironmentVariable("PYTHONPATH",EnvironmentVariableTarget.Process);}}}
Here are some related posts with more information.