I am trying to embed python 2.6 in .NET 4.0.
Following the very minimal documentation in "Python for .NET", I wrote a fairly straightforward code as follows:
const string pythonModulePath = @"C:\Projects\PythonImport\PythonImport\test.py";
Environment.SetEnvironmentVariable("PYTHONHOME", Path.GetDirectoryName(python
ModulePath));
PythonEngine.Initialize();
var oldWorkingDirectory = Directory.GetCurrentDirectory();
var currWorkingDirectory = Path.GetDirectoryName(pythonModulePath);
Directory.SetCurrentDirectory(currWorkingDirectory);
var pyPlugin = PythonEngine.ImportModule(Path.GetFileNameWithoutExtension(python
ModulePath));
if (pyPlugin == null)
{
throw new PythonException();
}
Directory.SetCurrentDirectory(oldWorkingDirectory);
Even if test.py is empty I get an import error saying "No module named warnings".
'import site' failed; use -v for traceback
Unhandled Exception: Python.Runtime.PythonException: ImportError : No module nam
ed warnings
The reason becomes apparent when you run test.py using "python -v" (verbose mode). Notice that python calls #cleanup[2] warnings.
Why is Python .NET not able to resolve warnings? The module is present in Lib directory.
Any ideas?
I think by default the Python Engine does not set the paths you need automatically.
http://www.voidspace.org.uk/ironpython/custom_executable.shtml has an example for embedding ironpython. Looks like you are missing something like
PythonEngine engine = new PythonEngine();
engine.AddToPath(Path.GetDirectoryName(Application.ExecutablePath));
engine.AddToPath(MyPathToStdLib);
Unless I know where and if Ironpython is installed, I prefer to find all of the standard modules I need, compile them to a IPyStdLibDLL and then do th following from my code
import clr
clr.addReference("IPyStdLib")
import site
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With