/// <summary> /// ReloadModule Method /// </summary> /// <remarks> /// Given a PyObject representing a previously loaded module, reload /// the module. /// </remarks> public static PyObject ReloadModule(PyObject module) { IntPtr op = Runtime.PyImport_ReloadModule(module.Handle); Runtime.CheckExceptionOccurred(); return(new PyObject(op)); }
public static PyObject ImportModule(string name) { if (!objs.ContainsKey(name)) { IntPtr op = Runtime.PyImport_ImportModule(name); if (op == IntPtr.Zero || op == Runtime.PyNone) { for (int i = 0; i < 10; i++) { System.Threading.Thread.Sleep(100); Console.WriteLine("-------------------- Import Error TRY(" + i + "): " + name); op = Runtime.PyImport_ImportModule(name); if (op != IntPtr.Zero && op != Runtime.PyNone) { break; } } if (op == IntPtr.Zero || op == Runtime.PyNone) { Console.WriteLine("-------------------- Import Error FINAL: " + name); Runtime.CheckExceptionOccurred(); } } objs.TryAdd(name, new PyObject(op)); } return(objs[name]); }
/// <summary> /// AsTuple Method /// </summary> /// <remarks> /// Convert a Python object to a Python tuple if possible, raising /// a PythonException if the conversion is not possible. This is /// equivalent to the Python expression "tuple(object)". /// </remarks> public static PyTuple AsTuple(PyObject value) { IntPtr op = Runtime.PySequence_Tuple(value.obj); Runtime.CheckExceptionOccurred(); return(new PyTuple(op)); }
/// <summary> /// AsInt Method /// </summary> /// <remarks> /// Convert a Python object to a Python int if possible, raising /// a PythonException if the conversion is not possible. This is /// equivalent to the Python expression "int(object)". /// </remarks> public static PyInt AsInt(PyObject value) { IntPtr op = Runtime.PyNumber_Int(value.obj); Runtime.CheckExceptionOccurred(); return(new PyInt(op)); }
private void DisposeAll() { CollectOnce?.Invoke(this, new CollectArgs() { ObjectCount = _objQueue.Count }); #if FINALIZER_CHECK lock (_queueLock) #endif { #if FINALIZER_CHECK ValidateRefCount(); #endif IPyDisposable obj; while (_objQueue.TryDequeue(out obj)) { try { obj.Dispose(); Runtime.CheckExceptionOccurred(); } catch (Exception e) { // We should not bother the main thread ErrorHandler?.Invoke(this, new ErrorArgs() { Error = e }); } } } }
/// <summary> /// AsLong Method /// </summary> /// <remarks> /// Convert a Python object to a Python long if possible, raising /// a PythonException if the conversion is not possible. This is /// equivalent to the Python expression "long(object)". /// </remarks> public static PyLong AsLong(PyObject value) { IntPtr op = Runtime.Interop.PyNumber_Long(value.obj); Runtime.CheckExceptionOccurred(); return(new PyLong(op)); }
/// <summary> /// AsFloat Method /// </summary> /// <remarks> /// Convert a Python object to a Python float if possible, raising /// a PythonException if the conversion is not possible. This is /// equivalent to the Python expression "float(object)". /// </remarks> public static PyFloat AsFloat(PyObject value) { IntPtr op = Runtime.Interop.PyNumber_Float(value.obj); Runtime.CheckExceptionOccurred(); return(new PyFloat(op)); }
/// <summary> /// ImportModule Method /// </summary> /// <remarks> /// Given a fully-qualified module or package name, import the /// module and return the resulting module object as a PyObject /// or null if an exception is raised. /// </remarks> public static PyObject ImportModule(string name) { IntPtr op = Runtime.PyImport_ImportModule(name); Runtime.CheckExceptionOccurred(); return(new PyObject(op)); }
public static PyObject Compile(string code, string filename = "", RunFlagType mode = RunFlagType.File) { var flag = (IntPtr)mode; IntPtr ptr = Runtime.Py_CompileString(code, filename, flag); Runtime.CheckExceptionOccurred(); return(new PyObject(ptr)); }
/// <summary> /// PyFloat Constructor /// </summary> /// <remarks> /// Creates a new Python float from a string value. /// </remarks> public PyFloat(string value) { using (var s = new PyString(value)) { obj = Runtime.PyFloat_FromString(s.obj, IntPtr.Zero); Runtime.CheckExceptionOccurred(); } }
public static void SetArgv(IEnumerable <string> argv) { using (GIL()) { string[] arr = argv.ToArray(); Runtime.PySys_SetArgvEx(arr.Length, arr, 0); Runtime.CheckExceptionOccurred(); } }
private void DisposeAll() { BeforeCollect?.Invoke(this, new CollectArgs() { ObjectCount = _objQueue.Count }); #if FINALIZER_CHECK lock (_queueLock) #endif { #if FINALIZER_CHECK ValidateRefCount(); #endif IntPtr obj; Runtime.PyErr_Fetch(out var errType, out var errVal, out var traceback); try { while (!_objQueue.IsEmpty) { if (!_objQueue.TryDequeue(out obj)) { continue; } Runtime.XDecref(obj); try { Runtime.CheckExceptionOccurred(); } catch (Exception e) { var errorArgs = new ErrorArgs { Error = e, }; ErrorHandler?.Invoke(this, errorArgs); if (!errorArgs.Handled) { throw new FinalizationException( "Python object finalization failed", disposable: obj, innerException: e); } } } } finally { // Python requires finalizers to preserve exception: // https://docs.python.org/3/extending/newtypes.html#finalization-and-de-allocation Runtime.PyErr_Restore(errType.StealNullable(), errVal.StealNullable(), traceback.StealNullable()); } } }
/// <summary> /// ReloadModule Method /// </summary> /// <remarks> /// Given a PyObject representing a previously loaded module, reload /// the module. /// </remarks> public static PyObject ReloadModule(PyObject module) { IntPtr op = Runtime.PyImport_ReloadModule(module.Handle); if (op == IntPtr.Zero || op == Runtime.PyNone) { Runtime.CheckExceptionOccurred(); } return(new PyObject(op)); }
/// <summary> /// ModuleFromString Method /// </summary> /// <remarks> /// Given a string module name and a string containing Python code, /// execute the code in and return a module of the given name. /// </remarks> public static PyObject ModuleFromString(string name, string code) { IntPtr c = Runtime.Py_CompileString(code, "none", (IntPtr)257); Runtime.CheckExceptionOccurred(); IntPtr m = Runtime.PyImport_ExecCodeModule(name, c); Runtime.CheckExceptionOccurred(); return(new PyObject(m)); }
private void DisposeAll() { #if DEBUG // only used for testing CollectOnce?.Invoke(this, new CollectArgs() { ObjectCount = _objQueue.Count }); #endif #if FINALIZER_CHECK lock (_queueLock) #endif { #if FINALIZER_CHECK ValidateRefCount(); #endif IntPtr obj; Runtime.PyErr_Fetch(out var errType, out var errVal, out var traceback); try { while (_objQueue.TryDequeue(out obj)) { Runtime.XDecref(obj); try { Runtime.CheckExceptionOccurred(); } catch (Exception e) { var handler = ErrorHandler; if (handler is null) { throw new FinalizationException( "Python object finalization failed", disposable: obj, innerException: e); } handler.Invoke(this, new ErrorArgs() { Error = e }); } } } finally { // Python requires finalizers to preserve exception: // https://docs.python.org/3/extending/newtypes.html#finalization-and-de-allocation Runtime.PyErr_Restore(errType, errVal, traceback); } } }
/// <summary> /// Eval method /// </summary> /// <remarks> /// Evaluate a Python expression and return the result as a PyObject /// or null if an exception is raised. /// </remarks> public PyObject Eval(string code, PyDict locals = null) { Check(); IntPtr _locals = locals == null ? variables : locals.obj; var flag = (IntPtr)Runtime.Py_eval_input; IntPtr ptr = Runtime.PyRun_String( code, flag, variables, _locals ); Runtime.CheckExceptionOccurred(); return(new PyObject(ptr)); }
/// <summary> /// PyTuple Constructor /// </summary> /// <remarks> /// Creates a new PyTuple from an array of PyObject instances. /// <para /> /// See caveats about PyTuple_SetItem: /// https://www.coursehero.com/file/p4j2ogg/important-exceptions-to-this-rule-PyTupleSetItem-and-PyListSetItem-These/ /// </remarks> public PyTuple(PyObject[] items) { int count = items.Length; obj = Runtime.PyTuple_New(count); for (var i = 0; i < count; i++) { IntPtr ptr = items[i].obj; Runtime.XIncref(ptr); Runtime.PyTuple_SetItem(obj, i, ptr); Runtime.CheckExceptionOccurred(); } }
private void Exec(string code, IntPtr _globals, IntPtr _locals) { var flag = (IntPtr)Runtime.Py_file_input; IntPtr ptr = Runtime.PyRun_String( code, flag, _globals, _locals ); Runtime.CheckExceptionOccurred(); if (ptr != Runtime.PyNone) { throw new PythonException(); } Runtime.XDecref(ptr); }
/// <summary> /// Execute method /// </summary> /// <remarks> /// Execute a Python ast and return the result as a PyObject. /// The ast can be either an expression or stmts. /// </remarks> public PyObject Execute(PyObject script, PyDict locals = null) { Check(); IntPtr _locals = locals == null ? variables : locals.obj; IntPtr ptr = Runtime.PyEval_EvalCode(script.Handle, variables, _locals); Runtime.CheckExceptionOccurred(); if (ptr == Runtime.PyNone) { Runtime.XDecref(ptr); return(null); } return(new PyObject(ptr)); }
/// <summary> /// Internal RunString Method. /// </summary> /// <remarks> /// Run a string containing Python code. Returns the result of /// executing the code string as a PyObject instance, or null if /// an exception was raised. /// </remarks> internal static PyObject RunString(string code, IntPtr?globals, IntPtr?locals, RunFlagType flag) { var borrowedGlobals = true; if (globals == null) { globals = Runtime.PyEval_GetGlobals(); if (globals == IntPtr.Zero) { globals = Runtime.PyDict_New(); Runtime.PyDict_SetItemString( globals.Value, "__builtins__", Runtime.PyEval_GetBuiltins() ); borrowedGlobals = false; } } if (locals == null) { locals = globals; } try { NewReference result = Runtime.PyRun_String( code, (IntPtr)flag, globals.Value, locals.Value ); try { Runtime.CheckExceptionOccurred(); return(result.MoveToPyObject()); } finally { result.Dispose(); } } finally { if (!borrowedGlobals) { Runtime.XDecref(globals.Value); } } }
/// <summary> /// ModuleFromString Method /// </summary> /// <remarks> /// Given a string module name and a string containing Python code, /// execute the code in and return a module of the given name. /// </remarks> public static PyObject ModuleFromString(string name, string code) { IntPtr c = Runtime.Py_CompileString(code, "none", (IntPtr)257); Runtime.CheckExceptionOccurred(); IntPtr m = Runtime.PyImport_ExecCodeModule(name, c); Runtime.CheckExceptionOccurred(); PyObject res = new PyObject(m); if (!objs.ContainsKey(name)) { objs.TryAdd(name, res); } return(res); }
/// <summary> /// Constructor /// </summary> /// <remarks> /// Create a scope based on a Python Module. /// </remarks> internal PyScope(IntPtr ptr, PyScopeManager manager) { if (!Runtime.Interop.PyType_IsSubtype(Runtime.PyObject_TYPE(ptr), Runtime.PyModuleType)) { throw new PyScopeException("object is not a module"); } Manager = manager ?? PyScopeManager.Global; obj = ptr; //Refcount of the variables not increase variables = Runtime.Interop.PyModule_GetDict(obj); Runtime.CheckExceptionOccurred(); Runtime.Interop.PyDict_SetItemString( variables, "__builtins__", Runtime.Interop.PyEval_GetBuiltins() ); this.Name = this.Get <string>("__name__"); }
public static PyObject CompileToModule(string name, string code, string filename = "", RunFlagType mode = RunFlagType.File) { var flag = (IntPtr)mode; IntPtr ptr = Runtime.Py_CompileString(code, filename, flag); Runtime.CheckExceptionOccurred(); IntPtr m = Runtime.PyImport_ExecCodeModule(name, ptr); Runtime.CheckExceptionOccurred(); PyObject res = new PyObject(m); if (!objs.ContainsKey(name)) { objs.TryAdd(name, res); } return(res); }
/// <summary> /// Dispose Method /// </summary> /// <remarks> /// The Dispose method provides a way to explicitly release the /// Python object represented by a PyObject instance. It is a good /// idea to call Dispose on PyObjects that wrap resources that are /// limited or need strict lifetime control. Otherwise, references /// to Python objects will not be released until a managed garbage /// collection occurs. /// </remarks> protected virtual void Dispose(bool disposing) { if (this.obj == IntPtr.Zero) { return; } if (Runtime.Py_IsInitialized() == 0) { throw new InvalidOperationException("Python runtime must be initialized"); } if (!Runtime.IsFinalizing) { long refcount = Runtime.Refcount(this.obj); Debug.Assert(refcount > 0, "Object refcount is 0 or less"); if (refcount == 1) { Runtime.PyErr_Fetch(out var errType, out var errVal, out var traceback); try { Runtime.XDecref(this.obj); Runtime.CheckExceptionOccurred(); } finally { // Python requires finalizers to preserve exception: // https://docs.python.org/3/extending/newtypes.html#finalization-and-de-allocation Runtime.PyErr_Restore(errType, errVal, traceback); } } else { Runtime.XDecref(this.obj); } } else { throw new InvalidOperationException("Runtime is already finalizing"); } this.obj = IntPtr.Zero; }
/// <summary> /// Eval method /// </summary> /// <remarks> /// Evaluate a Python expression and return the result as a PyObject /// or null if an exception is raised. /// </remarks> public PyObject Eval(string code, PyDict locals = null) { Check(); IntPtr _locals = locals == null ? variables : locals.obj; var flag = (IntPtr)Runtime.Py_eval_input; NewReference reference = Runtime.PyRun_String( code, flag, variables, _locals ); try { Runtime.CheckExceptionOccurred(); return(reference.MoveToPyObject()); } finally { reference.Dispose(); } }
private void Exec(string code, IntPtr _globals, IntPtr _locals) { var flag = (IntPtr)Runtime.Py_file_input; NewReference reference = Runtime.PyRun_String( code, flag, _globals, _locals ); try { Runtime.CheckExceptionOccurred(); if (!reference.IsNone()) { throw new PythonException(); } } finally { reference.Dispose(); } }
/// <summary> /// Convert a Python value to an instance of a primitive managed type. /// </summary> private static bool ToPrimitive(IntPtr value, Type obType, out object result, bool setError) { IntPtr overflow = Exceptions.OverflowError; TypeCode tc = Type.GetTypeCode(obType); result = null; IntPtr op; int ival; switch (tc) { case TypeCode.String: string st = Runtime.GetManagedString(value); if (st == null) { goto type_error; } result = st; return(true); case TypeCode.Int32: // Trickery to support 64-bit platforms. if (Runtime.IsPython2 && Runtime.Is32Bit) { op = Runtime.Interop.PyNumber_Int(value); // As of Python 2.3, large ints magically convert :( if (Runtime.PyLong_Check(op)) { Runtime.XDecref(op); goto overflow; } if (op == IntPtr.Zero) { if (Exceptions.ExceptionMatches(overflow)) { goto overflow; } goto type_error; } ival = (int)Runtime.Interop.PyInt_AsLong(op); Runtime.XDecref(op); result = ival; return(true); } else // Python3 always use PyLong API { op = Runtime.Interop.PyNumber_Long(value); if (op == IntPtr.Zero) { Exceptions.Clear(); if (Exceptions.ExceptionMatches(overflow)) { goto overflow; } goto type_error; } long ll = (long)Runtime.Interop.PyLong_AsLongLong(op); Runtime.XDecref(op); if (ll == -1 && Exceptions.ErrorOccurred()) { goto overflow; } if (ll > Int32.MaxValue || ll < Int32.MinValue) { goto overflow; } result = (int)ll; return(true); } case TypeCode.Boolean: result = Runtime.Interop.PyObject_IsTrue(value) != 0; return(true); case TypeCode.Byte: #if PYTHON3 if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { if (Runtime.Interop.PyBytes_Size(value) == 1) { op = Runtime.PyBytes_AS_STRING(value); result = (byte)Marshal.ReadByte(op); return(true); } goto type_error; } #elif PYTHON2 if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType)) { if (Runtime.PyString_Size(value) == 1) { op = Runtime.PyString_AsString(value); result = (byte)Marshal.ReadByte(op); return(true); } goto type_error; } #endif op = Runtime.Interop.PyNumber_Int(value); if (op == IntPtr.Zero) { if (Exceptions.ExceptionMatches(overflow)) { goto overflow; } goto type_error; } ival = (int)Runtime.Interop.PyInt_AsLong(op); Runtime.XDecref(op); if (ival > Byte.MaxValue || ival < Byte.MinValue) { goto overflow; } byte b = (byte)ival; result = b; return(true); case TypeCode.SByte: #if PYTHON3 if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { if (Runtime.Interop.PyBytes_Size(value) == 1) { op = Runtime.PyBytes_AS_STRING(value); result = (byte)Marshal.ReadByte(op); return(true); } goto type_error; } #elif PYTHON2 if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType)) { if (Runtime.PyString_Size(value) == 1) { op = Runtime.PyString_AsString(value); result = (sbyte)Marshal.ReadByte(op); return(true); } goto type_error; } #endif op = Runtime.Interop.PyNumber_Int(value); if (op == IntPtr.Zero) { if (Exceptions.ExceptionMatches(overflow)) { goto overflow; } goto type_error; } ival = (int)Runtime.Interop.PyInt_AsLong(op); Runtime.XDecref(op); if (ival > SByte.MaxValue || ival < SByte.MinValue) { goto overflow; } sbyte sb = (sbyte)ival; result = sb; return(true); case TypeCode.Char: #if PYTHON3 if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType)) { if (Runtime.Interop.PyBytes_Size(value) == 1) { op = Runtime.PyBytes_AS_STRING(value); result = (byte)Marshal.ReadByte(op); return(true); } goto type_error; } #elif PYTHON2 if (Runtime.PyObject_TypeCheck(value, Runtime.PyStringType)) { if (Runtime.PyString_Size(value) == 1) { op = Runtime.PyString_AsString(value); result = (char)Marshal.ReadByte(op); return(true); } goto type_error; } #endif else if (Runtime.PyObject_TypeCheck(value, Runtime.PyUnicodeType)) { if (Runtime.Interop.PyUnicode_GetSize(value) == 1) { op = Runtime.Interop.PyUnicode_AsUnicode(value); Char[] buff = new Char[1]; Marshal.Copy(op, buff, 0, 1); result = buff[0]; return(true); } goto type_error; } op = Runtime.Interop.PyNumber_Int(value); if (op == IntPtr.Zero) { goto type_error; } ival = Runtime.Interop.PyInt_AsLong(op); Runtime.XDecref(op); if (ival > Char.MaxValue || ival < Char.MinValue) { goto overflow; } result = (char)ival; return(true); case TypeCode.Int16: op = Runtime.Interop.PyNumber_Int(value); if (op == IntPtr.Zero) { if (Exceptions.ExceptionMatches(overflow)) { goto overflow; } goto type_error; } ival = (int)Runtime.Interop.PyInt_AsLong(op); Runtime.XDecref(op); if (ival > Int16.MaxValue || ival < Int16.MinValue) { goto overflow; } short s = (short)ival; result = s; return(true); case TypeCode.Int64: op = Runtime.Interop.PyNumber_Long(value); if (op == IntPtr.Zero) { if (Exceptions.ExceptionMatches(overflow)) { goto overflow; } goto type_error; } long l = (long)Runtime.Interop.PyLong_AsLongLong(op); Runtime.XDecref(op); if ((l == -1) && Exceptions.ErrorOccurred()) { goto overflow; } result = l; return(true); case TypeCode.UInt16: op = Runtime.Interop.PyNumber_Int(value); if (op == IntPtr.Zero) { if (Exceptions.ExceptionMatches(overflow)) { goto overflow; } goto type_error; } ival = (int)Runtime.Interop.PyInt_AsLong(op); Runtime.XDecref(op); if (ival > UInt16.MaxValue || ival < UInt16.MinValue) { goto overflow; } ushort us = (ushort)ival; result = us; return(true); case TypeCode.UInt32: op = Runtime.Interop.PyNumber_Long(value); if (op == IntPtr.Zero) { if (Exceptions.ExceptionMatches(overflow)) { goto overflow; } goto type_error; } uint ui = (uint)Runtime.Interop.PyLong_AsUnsignedLong(op); if (Exceptions.ErrorOccurred()) { Runtime.XDecref(op); goto overflow; } IntPtr check = Runtime.Interop.PyLong_FromUnsignedLong(ui); int err = Runtime.PyObject_Compare(check, op); Runtime.XDecref(check); Runtime.XDecref(op); if (0 != err || Exceptions.ErrorOccurred()) { goto overflow; } result = ui; return(true); case TypeCode.UInt64: op = Runtime.Interop.PyNumber_Long(value); if (op == IntPtr.Zero) { if (Exceptions.ExceptionMatches(overflow)) { goto overflow; } goto type_error; } ulong ul = (ulong)Runtime.Interop.PyLong_AsUnsignedLongLong(op); Runtime.XDecref(op); if (Exceptions.ErrorOccurred()) { goto overflow; } result = ul; return(true); case TypeCode.Single: op = Runtime.Interop.PyNumber_Float(value); if (op == IntPtr.Zero) { if (Exceptions.ExceptionMatches(overflow)) { goto overflow; } goto type_error; } double dd = Runtime.Interop.PyFloat_AsDouble(op); Runtime.CheckExceptionOccurred(); Runtime.XDecref(op); if (dd > Single.MaxValue || dd < Single.MinValue) { if (!double.IsInfinity(dd)) { goto overflow; } } result = (float)dd; return(true); case TypeCode.Double: op = Runtime.Interop.PyNumber_Float(value); if (op == IntPtr.Zero) { goto type_error; } double d = Runtime.Interop.PyFloat_AsDouble(op); Runtime.CheckExceptionOccurred(); Runtime.XDecref(op); result = d; return(true); } type_error: if (setError) { string tpName = Runtime.PyObject_GetTypeName(value); Exceptions.SetError(Exceptions.TypeError, $"'{tpName}' value cannot be converted to {obType}"); } return(false); overflow: if (setError) { Exceptions.SetError(Exceptions.OverflowError, "value too large to convert"); } return(false); }
/// <summary> /// PyFloat Constructor /// </summary> /// <remarks> /// Creates a new Python float from a double value. /// </remarks> public PyFloat(double value) { obj = Runtime.PyFloat_FromDouble(value); Runtime.CheckExceptionOccurred(); }
public PyInt(ulong value) { obj = Runtime.PyInt_FromInt64((long)value); Runtime.CheckExceptionOccurred(); }
public PyInt(uint value) { obj = Runtime.PyInt_FromInt64(value); Runtime.CheckExceptionOccurred(); }