InvokeMethod() public method

InvokeMethod Method
Invoke the named method of the object with the given arguments. A PythonException is raised if the invokation is unsuccessful.
public InvokeMethod ( string name ) : PyObject
name string
return PyObject
Example #1
0
        public static void With(PyObject obj, Action <dynamic> Body)
        {
            // Behavior described here:
            // https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers

            IntPtr          type      = Runtime.PyNone;
            IntPtr          val       = Runtime.PyNone;
            IntPtr          traceBack = Runtime.PyNone;
            PythonException ex        = null;

            try
            {
                PyObject enterResult = obj.InvokeMethod("__enter__");

                Body(enterResult);
            }
            catch (PythonException e)
            {
                ex        = e;
                type      = ex.PyType.Coalesce(type);
                val       = ex.PyValue.Coalesce(val);
                traceBack = ex.PyTB.Coalesce(traceBack);
            }

            Runtime.XIncref(type);
            Runtime.XIncref(val);
            Runtime.XIncref(traceBack);
            var exitResult = obj.InvokeMethod("__exit__", new PyObject(type), new PyObject(val), new PyObject(traceBack));

            if (ex != null && !exitResult.IsTrue())
            {
                throw ex;
            }
        }
Example #2
0
        public static PyObject NewArray(Array content)
        {
            // BlockCopy possibly multidimensional array of arbitrary type to onedimensional byte array
            System.Type ElementType = content.GetType().GetElementType();
            int         nbytes      = content.Length * Marshal.SizeOf(ElementType);

            byte[] data = new byte[nbytes];
            System.Buffer.BlockCopy(content, 0, data, 0, nbytes);

            // Create an python tuple with the dimensions of the input array
            PyObject[] lengths = new PyObject[content.Rank];
            for (int i = 0; i < content.Rank; i++)
            {
                lengths[i] = new PyInt(content.GetLength(i));
            }
            PyTuple shape = new PyTuple(lengths);

            // Create an empty numpy array in correct shape and datatype
            var dtype = GetNumpyDataType(ElementType);
            var arr   = np.InvokeMethod("empty", shape, dtype);

            var meta    = arr.GetAttr("__array_interface__");
            var address = new System.IntPtr((long)meta["data"][0].As <long>());

            // Copy the data to that array
            Marshal.Copy(data, 0, address, nbytes);
            return(arr);
        }
        public PythonException()
        {
            IntPtr gs = PythonEngine.AcquireLock();

            Runtime.PyErr_Fetch(out _pyType, out _pyValue, out _pyTB);
            if (_pyType != IntPtr.Zero && _pyValue != IntPtr.Zero)
            {
                string type;
                string message;
                Runtime.XIncref(_pyType);
                using (var pyType = new PyObject(_pyType))
                    using (PyObject pyTypeName = pyType.GetAttr("__name__"))
                    {
                        type = pyTypeName.ToString();
                    }

                _pythonTypeName = type;

                // TODO: If pyValue has a __cause__ attribute, then we could set this.InnerException to the equivalent managed exception.
                Runtime.XIncref(_pyValue);
                using (var pyValue = new PyObject(_pyValue))
                {
                    message = pyValue.ToString();
                }
                _message = type + " : " + message;
            }

            if (_pyTB != IntPtr.Zero)
            {
                using PyObject tb_module = PythonEngine.ImportModule("traceback");

                Runtime.XIncref(_pyTB);
                using var pyTB = new PyObject(_pyTB);

                using var tbList = tb_module.InvokeMethod("format_tb", pyTB);

                var sb = new StringBuilder();
                // Reverse Python's traceback list to match the order used in C#
                // stacktraces
                foreach (var line in tbList.Reverse())
                {
                    sb.Append(line.ToString());
                }
                _tb = sb.ToString();
            }
            PythonEngine.ReleaseLock(gs);
        }
Example #4
0
        public static byte[] SaveFigureToArray(PyObject fig, int dpi = 200, string format = "png")
        {
            if (fig.GetPythonType().Handle != PltFigureType)
            {
                throw new Exception("object is not a matplotlib Figure");
            }

            dynamic _np = np;
            //buf = io.BytesIO()
            dynamic buf = BytesIO.Invoke();

            //fig.savefig(buf, dpi=__dpi__, format='png')
            fig.InvokeMethod("savefig", new PyTuple(new PyObject[] { buf }), Py.kw("dpi", dpi, "format", format));
            var buf_out = _np.array(buf.getbuffer(), Py.kw("dtype", Numpy.GetNumpyDataType(typeof(byte))));
            var arr     = Numpy.ToArray(buf_out);

            return((byte[])arr);
        }
Example #5
0
        /// <summary>
        /// Formats this PythonException object into a message as would be printed
        /// out via the Python console. See traceback.format_exception
        /// </summary>
        public string Format()
        {
            string res;
            IntPtr gs = PythonEngine.AcquireLock();

            try
            {
                if (_pyTB != IntPtr.Zero && _pyType != IntPtr.Zero && _pyValue != IntPtr.Zero)
                {
                    IntPtr tb    = _pyTB;
                    IntPtr type  = _pyType;
                    IntPtr value = _pyValue;

                    Runtime.XIncref(type);
                    Runtime.XIncref(value);
                    Runtime.XIncref(tb);
                    Runtime.PyErr_NormalizeException(ref type, ref value, ref tb);

                    using (PyObject pyType = new PyObject(type))
                        using (PyObject pyValue = new PyObject(value))
                            using (PyObject pyTB = new PyObject(tb))
                                using (PyObject tb_mod = PyModule.Import("traceback"))
                                {
                                    var buffer = new StringBuilder();
                                    var values = tb_mod.InvokeMethod("format_exception", pyType, pyValue, pyTB);
                                    foreach (PyObject val in values)
                                    {
                                        buffer.Append(val.ToString());
                                    }
                                    res = buffer.ToString();
                                }
                }
                else
                {
                    res = StackTrace;
                }
            }
            finally
            {
                PythonEngine.ReleaseLock(gs);
            }
            return(res);
        }
Example #6
0
        public PythonException() : base()
        {
            Runtime.PyErr_Fetch(ref _pyType, ref _pyValue, ref _pyTB);
            Runtime.Incref(_pyType);
            Runtime.Incref(_pyValue);
            Runtime.Incref(_pyTB);
            IntPtr gs = PythonEngine.AcquireLock();

            if ((_pyType != IntPtr.Zero) && (_pyValue != IntPtr.Zero))
            {
                string type    = new PyObject(_pyType).GetAttr("__name__").ToString();
                string message = Runtime.GetManagedString(_pyValue);
                _message = type + " : " + message;
            }
            if (_pyTB != IntPtr.Zero)
            {
                PyObject tb_module = PythonEngine.ImportModule("traceback");
                _tb = tb_module.InvokeMethod("format_tb", new PyObject(_pyTB)).ToString();
            }
            PythonEngine.ReleaseLock(gs);
        }
Example #7
0
        public PythonException()
        {
            IntPtr gs = PythonEngine.AcquireLock();

            Runtime.Interop.PyErr_Fetch(ref _pyType, ref _pyValue, ref _pyTB);
            Runtime.XIncref(_pyType);
            Runtime.XIncref(_pyValue);
            Runtime.XIncref(_pyTB);
            if (_pyType != IntPtr.Zero && _pyValue != IntPtr.Zero)
            {
                string type;
                string message;
                Runtime.XIncref(_pyType);
                using (var pyType = new PyObject(_pyType))
                    using (PyObject pyTypeName = pyType.GetAttr("__name__"))
                    {
                        type = pyTypeName.ToString();
                    }

                _pythonTypeName = type;

                Runtime.XIncref(_pyValue);
                using (var pyValue = new PyObject(_pyValue))
                {
                    message = pyValue.ToString();
                }
                _message = type + " : " + message;
            }
            if (_pyTB != IntPtr.Zero)
            {
                PyObject tb_module = PythonEngine.ImportModule("traceback");
                Runtime.XIncref(_pyTB);
                using (var pyTB = new PyObject(_pyTB))
                {
                    _tb = tb_module.InvokeMethod("format_tb", pyTB).ToString();
                }
            }
            PythonEngine.ReleaseLock(gs);
        }
Example #8
0
 public static string get_backend()
 {
     return(matplotlib.InvokeMethod("get_backend").ToString());
 }