Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for .NET: ImportError: No module named warnings

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?

like image 945
sdeveloper Avatar asked Jan 17 '11 11:01

sdeveloper


1 Answers

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
like image 107
WombatPM Avatar answered Sep 21 '22 05:09

WombatPM