public IEnumerator <T> GetEnumerator() { PyObject iterObject; using (Py.GIL()) { var iter = Runtime.PyObject_GetIter(pyObject.Reference); PythonException.ThrowIfIsNull(iter); iterObject = iter.MoveToPyObject(); } while (true) { using (Py.GIL()) { var item = Runtime.PyIter_Next(iterObject.Handle); if (item == IntPtr.Zero) { Runtime.CheckExceptionOccurred(); iterObject.Dispose(); break; } yield return((T) new PyObject(item).AsManagedObject(typeof(T))); } } }
public void TestUnpickleException() { // python 2.x PythonException x = (PythonException)U("cexceptions\nZeroDivisionError\np0\n(S'hello'\np1\ntp2\nRp3\n."); Assert.Equal("[exceptions.ZeroDivisionError] hello", x.Message); Assert.Equal("exceptions.ZeroDivisionError", x.PythonExceptionType); // python 3.x x = (PythonException)U("c__builtin__\nZeroDivisionError\np0\n(Vhello\np1\ntp2\nRp3\n."); Assert.Equal("[__builtin__.ZeroDivisionError] hello", x.Message); Assert.Equal("__builtin__.ZeroDivisionError", x.PythonExceptionType); x = (PythonException)U("cbuiltins\nZeroDivisionError\np0\n(Vhello\np1\ntp2\nRp3\n."); Assert.Equal("[builtins.ZeroDivisionError] hello", x.Message); Assert.Equal("builtins.ZeroDivisionError", x.PythonExceptionType); // python 2.x x = (PythonException)U("cexceptions\nGeneratorExit\np0\n(tRp1\n."); Assert.Null(x.InnerException); Assert.Equal("exceptions.GeneratorExit", x.PythonExceptionType); // python 3.x x = (PythonException)U("c__builtin__\nGeneratorExit\np0\n(tRp1\n."); Assert.Equal("[__builtin__.GeneratorExit]", x.Message); Assert.Equal("__builtin__.GeneratorExit", x.PythonExceptionType); x = (PythonException)U("cbuiltins\nGeneratorExit\np0\n(tRp1\n."); Assert.Equal("[builtins.GeneratorExit]", x.Message); Assert.Equal("builtins.GeneratorExit", x.PythonExceptionType); }
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; } }
public static void PyCheck_Iter_PyObject_IsIterable_ThreadingLock_Test() { Runtime.Runtime.Py_Initialize(); Runtime.Native.ABI.Initialize(Runtime.Runtime.PyVersion); try { // Create an instance of threading.Lock, which is one of the very few types that does not have the // TypeFlags.HaveIter set in Python 2. This tests a different code path in PyObject_IsIterable and PyIter_Check. using var threading = Runtime.Runtime.PyImport_ImportModule("threading"); Exceptions.ErrorCheck(threading); var threadingDict = Runtime.Runtime.PyModule_GetDict(threading); Exceptions.ErrorCheck(threadingDict); var lockType = Runtime.Runtime.PyDict_GetItemString(threadingDict, "Lock"); if (lockType.IsNull) { throw PythonException.ThrowLastAsClrException(); } using var args = NewReference.DangerousFromPointer(Runtime.Runtime.PyTuple_New(0)); using var lockInstance = Runtime.Runtime.PyObject_CallObject(lockType, args); Exceptions.ErrorCheck(lockInstance); Assert.IsFalse(Runtime.Runtime.PyObject_IsIterable(lockInstance)); Assert.IsFalse(Runtime.Runtime.PyIter_Check(lockInstance)); } finally { Runtime.Runtime.Py_Finalize(); } }
public void TestNoError() { // There is no PyErr to fetch Assert.Throws <InvalidOperationException>(() => PythonException.FetchCurrentRaw()); var currentError = PythonException.FetchCurrentOrNullRaw(); Assert.IsNull(currentError); }
public AD7DebugExceptionDetails(PythonException exception) { if (exception == null) { throw new ArgumentNullException(nameof(exception)); } _exception = exception; }
public void TestPythonException_Normalize_ThrowsWhenErrorSet() { Exceptions.SetError(Exceptions.TypeError, "Error!"); var pythonException = new PythonException(); Exceptions.SetError(Exceptions.TypeError, "Another error"); Assert.Throws <InvalidOperationException>(() => pythonException.Normalize()); }
public void CanBorrowFromNewReference() { var dict = new PyDict(); using NewReference reference = Runtime.PyDict_Items(dict.Reference); BorrowedReference borrowed = reference.BorrowOrThrow(); PythonException.ThrowIfIsNotZero(Runtime.PyList_Reverse(borrowed)); }
public static IntPtr DoThrowSimple() { using (Py.GIL()) { dynamic builtins = Py.Import("builtins"); var typeErrorType = new PyType(builtins.TypeError); var pyerr = new PythonException(typeErrorType, value: null, traceback: null, "Type error, the first", innerException: null); throw new ArgumentException("Bogus bad parameter", pyerr); } }
public void testPythonExceptionType() { var ex = new PythonException("hello"); var type = ex.GetType(); var prop = type.GetProperty("PythonExceptionType"); Assert.IsNotNull(prop, "python exception class has to have a property PythonExceptionType, it is used in constructor classes"); prop = type.GetProperty("_pyroTraceback"); Assert.IsNotNull(prop, "python exception class has to have a property _pyroTraceback, it is used in constructor classes"); }
public override ValueType Execute(ValueType arg) { const string code = @" from Python.EmbeddingTest.Domain import MyClass def test_obj_call(): obj = MyClass() obj.Method() obj.StaticMethod() obj.Property = 1 obj.Field = 10 test_obj_call() "; const string name = "test_domain_reload_mod"; using (Py.GIL()) { // Create a new module IntPtr module = PyRuntime.PyModule_New(name); Assert.That(module != IntPtr.Zero); IntPtr globals = PyRuntime.PyObject_GetAttrString(module, "__dict__"); Assert.That(globals != IntPtr.Zero); try { // import builtins // module.__dict__[__builtins__] = builtins int res = PyRuntime.PyDict_SetItemString(globals, "__builtins__", PyRuntime.PyEval_GetBuiltins()); PythonException.ThrowIfIsNotZero(res); // Execute the code in the module's scope PythonEngine.Exec(code, globals); // import sys // modules = sys.modules IntPtr modules = PyRuntime.PyImport_GetModuleDict(); // modules[name] = module res = PyRuntime.PyDict_SetItemString(modules, name, module); PythonException.ThrowIfIsNotZero(res); } catch { PyRuntime.XDecref(module); throw; } finally { PyRuntime.XDecref(globals); } return(module); } }
public void CanBorrowFromNewReference() { var dict = new PyDict(); NewReference reference = Runtime.PyDict_Items(dict.Handle); try { PythonException.ThrowIfIsNotZero(Runtime.PyList_Reverse(reference)); } finally { reference.Dispose(); } }
public void Setup() { using (Py.GIL()) { try { // importing a module with syntax error 'x = 01' will throw PythonEngine.ModuleFromString(Guid.NewGuid().ToString(), "x = 01"); } catch (PythonException pythonException) { _pythonException = pythonException; } } }
public override ValueType Execute(ValueType arg) { var module = (IntPtr)arg; using (Py.GIL()) { var test_obj_call = PyRuntime.PyObject_GetAttrString(module, "test_obj_call"); PythonException.ThrowIfIsNull(test_obj_call); var args = PyRuntime.PyTuple_New(0); var res = PyRuntime.PyObject_CallObject(test_obj_call, args); PythonException.ThrowIfIsNull(res); PyRuntime.XDecref(args); PyRuntime.XDecref(res); } return 0; }
public void Setup() { using (Py.GIL()) { var module = Py.Import("Test_PythonExceptionInterpreter"); dynamic algorithm = module.GetAttr("Test_PythonExceptionInterpreter").Invoke(); try { // dict()['SPY'] algorithm.key_error(); } catch (PythonException pythonException) { _pythonException = pythonException; } } }
public void Setup() { using (Py.GIL()) { var module = Py.Import("Test_PythonExceptionInterpreter"); dynamic algorithm = module.GetAttr("Test_PythonExceptionInterpreter").Invoke(); try { // x = 1 / 0 algorithm.zero_division_error(); } catch (PythonException pythonException) { _pythonException = pythonException; } } }
public void Setup() { using (Py.GIL()) { var module = Py.Import("Test_PythonExceptionInterpreter"); dynamic algorithm = module.GetAttr("Test_PythonExceptionInterpreter").Invoke(); try { // x = None + "Pepe Grillo" algorithm.unsupported_operand(); } catch (PythonException pythonException) { _pythonException = pythonException; } } }
public void Setup() { using (Py.GIL()) { var module = Py.Import("Test_PythonExceptionInterpreter"); dynamic algorithm = module.GetAttr("Test_PythonExceptionInterpreter").Invoke(); try { // self.SetCash('SPY') algorithm.no_method_match(); } catch (PythonException pythonException) { _pythonException = pythonException; } } }
public static void DoThrowWithInner() { using (Py.GIL()) { // create a TypeError dynamic builtins = Py.Import("builtins"); var pyerrFirst = new PythonException(new PyType(builtins.TypeError), value: null, traceback: null, "Type error, the first", innerException: null); // Create an ArgumentException, but as a python exception, with the previous type error as the inner exception var argExc = new ArgumentException("Bogus bad parameter", pyerrFirst); var argExcPyObj = argExc.ToPython(); var pyArgExc = new PythonException(argExcPyObj.GetPythonType(), value: null, traceback: null, argExc.Message, innerException: argExc.InnerException); // This object must be disposed explicitly or else we get a false-positive leak. argExcPyObj.Dispose(); // Then throw a TypeError with the ArgumentException-as-python-error exception as inner. var pyerrSecond = new PythonException(new PyType(builtins.TypeError), value: null, traceback: null, "Type error, the second", innerException: pyArgExc); throw pyerrSecond; } }
public void testUnpickleException() { // python 2.x PythonException x = (PythonException)U("cexceptions\nZeroDivisionError\np0\n(S'hello'\np1\ntp2\nRp3\n."); Assert.AreEqual("hello", x.Message); // python 3.x x = (PythonException)U("c__builtin__\nZeroDivisionError\np0\n(Vhello\np1\ntp2\nRp3\n."); Assert.AreEqual("hello", x.Message); x = (PythonException)U("cbuiltins\nZeroDivisionError\np0\n(Vhello\np1\ntp2\nRp3\n."); Assert.AreEqual("hello", x.Message); // python 2.x x = (PythonException)U("cexceptions\nGeneratorExit\np0\n(tRp1\n."); Assert.IsNull(x.InnerException); // python 3.x x = (PythonException)U("c__builtin__\nGeneratorExit\np0\n(tRp1\n."); Assert.AreEqual("Exception of type 'Razorvine.Pickle.PythonException' was thrown.", x.Message); x = (PythonException)U("cbuiltins\nGeneratorExit\np0\n(tRp1\n."); Assert.AreEqual("Exception of type 'Razorvine.Pickle.PythonException' was thrown.", x.Message); }
public static NewReference CreateObjectType() { using var globals = Runtime.PyDict_New(); if (Runtime.PyDict_SetItemString(globals.Borrow(), "__builtins__", Runtime.PyEval_GetBuiltins()) != 0) { globals.Dispose(); throw PythonException.ThrowLastAsClrException(); } const string code = "class A(object): pass"; using var resRef = Runtime.PyRun_String(code, RunFlagType.File, globals.Borrow(), globals.Borrow()); if (resRef.IsNull()) { globals.Dispose(); throw PythonException.ThrowLastAsClrException(); } resRef.Dispose(); BorrowedReference A = Runtime.PyDict_GetItemString(globals.Borrow(), "A"); return(new NewReference(A)); }
public static IntPtr CreateObjectType() { using var globals = NewReference.DangerousFromPointer(Runtime.PyDict_New()); if (Runtime.PyDict_SetItemString(globals, "__builtins__", Runtime.PyEval_GetBuiltins()) != 0) { globals.Dispose(); throw PythonException.ThrowLastAsClrException(); } const string code = "class A(object): pass"; using var resRef = Runtime.PyRun_String(code, RunFlagType.File, globals, globals); if (resRef.IsNull()) { globals.Dispose(); throw PythonException.ThrowLastAsClrException(); } resRef.Dispose(); BorrowedReference A = Runtime.PyDict_GetItemString(globals, "A"); Debug.Assert(!A.IsNull); return(new NewReference(A).DangerousMoveToPointer()); }
public void Setup() { var pythonPath = new DirectoryInfo("RegressionAlgorithms"); Environment.SetEnvironmentVariable("PYTHONPATH", pythonPath.FullName); using (Py.GIL()) { var module = Py.Import("Test_PythonExceptionInterpreter"); dynamic algorithm = module.GetAttr("Test_PythonExceptionInterpreter").Invoke(); try { // x = 1 / 0 algorithm.zero_division_error(); } catch (PythonException pythonException) { _pythonException = pythonException; } } }
public void Setup() { var pythonPath = new DirectoryInfo("RegressionAlgorithms"); Environment.SetEnvironmentVariable("PYTHONPATH", pythonPath.FullName); using (Py.GIL()) { var module = Py.Import("Test_PythonExceptionInterpreter"); dynamic algorithm = module.GetAttr("Test_PythonExceptionInterpreter").Invoke(); try { // x = decimal.Decimal(1) * 1.1 algorithm.unsupported_operand(); } catch (PythonException pythonException) { _pythonException = pythonException; } } }
static void Main(string[] args) { PythonEngine.Initialize(); var globals = CreateGlobals(); while (true) { Console.Write(">>> "); var input = Console.ReadLine(); if (input == "exit()") { return; } using (Py.GIL()) { var ret = PythonEngine.RunString($"RESULTS_VARIABLE = {input}", globals.Handle, IntPtr.Zero); if (ret != null) { Console.WriteLine(globals.GetItem("RESULTS_VARIABLE")); } else { var exception = new PythonException(); ret = PythonEngine.RunString(input, globals.Handle, IntPtr.Zero); if (ret == null) { exception = new PythonException(); Console.WriteLine(exception.Message); } } } } }
public PyObject?TryEncode(object value) { if (value == null) { return(null); } var tupleType = value.GetType(); if (tupleType == typeof(object)) { return(null); } if (!this.CanEncode(tupleType)) { return(null); } if (tupleType == typeof(TTuple)) { return(new PyTuple()); } nint fieldCount = tupleType.GetGenericArguments().Length; using var tuple = Runtime.PyTuple_New(fieldCount); PythonException.ThrowIfIsNull(tuple); int fieldIndex = 0; foreach (FieldInfo field in tupleType.GetFields()) { var item = field.GetValue(value); using var pyItem = Converter.ToPython(item, field.FieldType); Runtime.PyTuple_SetItem(tuple.Borrow(), fieldIndex, pyItem.Steal()); fieldIndex++; } return(new PyTuple(tuple.Steal())); }
public XamlaPythonException(PythonException e) : base(e.Message, e) { IntPtr pyTBPython = e.PyTB; using (Py.GIL()) { if (pyTBPython != IntPtr.Zero) { PyObject tb_module = PythonEngine.ImportModule("traceback"); using (var pyTB = new PyObject(pyTBPython)) { var traceRaw = (List <string>)PyConvert.ToClrObject(tb_module.InvokeMethod("format_tb", pyTB), typeof(List <string>)); stackTraceElements = traceRaw.Select(i => Regex.Replace(i, @"\r\n?|\n", "")).ToList(); } stackTrace = String.Join(System.Environment.NewLine, stackTraceElements); } } message = String.Join(System.Environment.NewLine, new List <string> { e.Message, "Stack trace: ", stackTrace }); }
public static void With(PyObject obj, Action <dynamic> Body) { // Behavior described here: // https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers Exception ex = null; PythonException pyError = null; try { PyObject enterResult = obj.InvokeMethod("__enter__"); Body(enterResult); } catch (PythonException e) { ex = pyError = e; } catch (Exception e) { ex = e; Exceptions.SetError(e); pyError = PythonException.FetchCurrentRaw(); } PyObject type = pyError?.Type ?? PyObject.None; PyObject val = pyError?.Value ?? PyObject.None; PyObject traceBack = pyError?.Traceback ?? PyObject.None; var exitResult = obj.InvokeMethod("__exit__", type, val, traceBack); if (ex != null && !exitResult.IsTrue()) { throw ex; } }
public AD7DebugExceptionEvent(AD7Engine engine, PythonException exception) { _engine = engine; _exception = exception; }
public void TestNoError() { var e = new PythonException(); // There is no PyErr to fetch Assert.AreEqual("", e.Message); }