[Python.NET] Python.Net for Python3: bug when using an embedded interpreter

Serge WEINSTOCK serge.weinstock at uk.bnpparibas.com
Tue Sep 30 12:59:27 CEST 2014


Hi Tony,

You recently made a change which prevents me using the library in an embedded Python interpreter.

In pythonengine.cs, you "inject" decorators with the following code:

//=================================================================
public static void Initialize() {
.....
IntPtr globals = Runtime.PyEval_GetGlobals();
PyDict locals = new PyDict();
try
{
    IntPtr builtins = Runtime.PyEval_GetBuiltins();
    Runtime.PyDict_SetItemString(locals.Handle, "__builtins__", builtins);

    var assembly = Assembly.GetExecutingAssembly();
    using (Stream stream = assembly.GetManifestResourceStream("Python.Runtime.resources.clr.py"))
    using (StreamReader reader = new StreamReader(stream))
    {
        // add the contents of clr.py to the module
        string clr_py = reader.ReadToEnd();
        PyObject result = RunString(clr_py, globals, locals.Handle);
        if (null == result)
            throw new PythonException();
        result.Dispose();
    }
//=================================================================
When running from a Python script, it's fine because the Python interpreter has already been initialized and global variables have been defined.

The issue is that when running from an embedded interpreter. As I must first initialize the Python engine using PythonEngine.Initialize().

So when we reach this piece of code, there is no script running, no "Python context", so "PyEval_GetGlobals" returns null and "RunString" fails.

We could create an artificial global dictionary but it won't be available to the rest of the code.

I think it should be best to move this code into a Python module. If run from a script (PyEval_GetGlobals() != null), you could inject the decorators with a simple "from decorators_pythonnet import *". If run from an embedded interpreter, we could add a line for running the same code once the engine has been initialized.

What do you think?

Serge Weinstock


___________________________________________________________
This e-mail may contain confidential and/or privileged information. If you are not the intended recipient (or have received this e-mail in error) please notify the sender immediately and delete this e-mail. Any unauthorised copying, disclosure or distribution of the material in this e-mail is prohibited.

Please refer to http://www.bnpparibas.co.uk/en/email-disclaimer/ for additional disclosures.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pythondotnet/attachments/20140930/f79fe3e3/attachment.html>


More information about the PythonDotNet mailing list