[Python.NET] Updates to RunString

Michael Eddington meddington at gmail.com
Sat Oct 8 06:48:09 CEST 2005


Been playing around with RunString implementations looking for what
works best.  Here is my result.  I am able to run any python script
loaded from file just fine.  Also, between calls to RunString local
variables are saved just fine.

	protected static PyDict	locals = null;

	public static PyObject RunString(string code)
	{
		PyObject module = ImportModule("__main__");
		PyDict globals = new PyDict(Runtime.PyModule_GetDict(module.Handle));

        if (locals == null)
        {
            locals = new PyDict(Runtime.PyDict_New());
        }

        IntPtr result = Runtime.PyRun_String(code, (IntPtr)257,
globals.Handle, locals.Handle);

        if (result == IntPtr.Zero)
        {
            return null;
        }

        return new PyObject(result);
    }


More information about the PythonDotNet mailing list