/// <summary> /// Initialization performed on startup of the Python runtime. /// </summary> internal static void Initialize() { string exceptionsModuleName = Runtime.IsPython3 ? "builtins" : "exceptions"; exceptions_module = Runtime.PyImport_ImportModule(exceptionsModuleName); Exceptions.ErrorCheck(exceptions_module); warnings_module = Runtime.PyImport_ImportModule("warnings"); Exceptions.ErrorCheck(warnings_module); Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { IntPtr op = Runtime.PyObject_GetAttrString(exceptions_module, fi.Name); if (op != IntPtr.Zero) { fi.SetValue(type, op); } else { fi.SetValue(type, IntPtr.Zero); DebugUtil.Print($"Unknown exception: {fi.Name}"); } } Runtime.PyErr_Clear(); }
//==================================================================== // helper methods for raising warnings //==================================================================== /// <summary> /// Alias for Python's warnings.warn() function. /// </summary> public static void warn(string message, IntPtr exception, int stacklevel) { if (exception == IntPtr.Zero || (Runtime.PyObject_IsSubclass(exception, Exceptions.Warning) != 1)) { Exceptions.RaiseTypeError("Invalid exception"); } Runtime.XIncref(warnings_module); IntPtr warn = Runtime.PyObject_GetAttrString(warnings_module, "warn"); Runtime.XDecref(warnings_module); Exceptions.ErrorCheck(warn); IntPtr args = Runtime.PyTuple_New(3); IntPtr msg = Runtime.PyString_FromString(message); Runtime.XIncref(exception); // PyTuple_SetItem steals a reference IntPtr level = Runtime.PyInt_FromInt32(stacklevel); Runtime.PyTuple_SetItem(args, 0, msg); Runtime.PyTuple_SetItem(args, 1, exception); Runtime.PyTuple_SetItem(args, 2, level); IntPtr result = Runtime.PyObject_CallObject(warn, args); Exceptions.ErrorCheck(result); Runtime.XDecref(warn); Runtime.XDecref(result); Runtime.XDecref(args); }
//=================================================================== // Initialization performed on startup of the Python runtime. //=================================================================== internal static void Initialize() { #if (PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35) exceptions_module = Runtime.PyImport_ImportModule("builtins"); #else exceptions_module = Runtime.PyImport_ImportModule("exceptions"); #endif Exceptions.ErrorCheck(exceptions_module); warnings_module = Runtime.PyImport_ImportModule("warnings"); Exceptions.ErrorCheck(warnings_module); Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { IntPtr op = Runtime.PyObject_GetAttrString(exceptions_module, fi.Name); if (op != IntPtr.Zero) { fi.SetValue(type, op); } else { fi.SetValue(type, IntPtr.Zero); DebugUtil.Print("Unknown exception: " + fi.Name); } } Runtime.PyErr_Clear(); }
internal static IntPtr GetExceptionInstanceWrapper(IntPtr real) { // Given the pointer to a new-style class instance representing a // managed exception, return an appropriate old-style class // wrapper instance that delegates to the wrapped instance. IntPtr tp = Runtime.PyObject_TYPE(real); if (Runtime.PyObject_TYPE(tp) == Runtime.PyInstanceType) { return(real); } // Get / generate a class wrapper, instantiate it and set its // _inner attribute to the real new-style exception instance. IntPtr ct = GetExceptionClassWrapper(tp); Exceptions.ErrorCheck(ct); IntPtr op = Runtime.PyInstance_NewRaw(ct, IntPtr.Zero); Exceptions.ErrorCheck(op); IntPtr d = Runtime.PyObject_GetAttrString(op, "__dict__"); Exceptions.ErrorCheck(d); Runtime.PyDict_SetItemString(d, "_inner", real); Runtime.Decref(d); return(op); }
//==================================================================== // helper methods for raising warnings //==================================================================== /// <summary> /// Alias for Python's warnings.warn() function. /// </summary> public static void warn(string message, BorrowedReference exception, int stacklevel) { if (exception == null || (Runtime.PyObject_IsSubclass(exception, Exceptions.Warning) != 1)) { Exceptions.RaiseTypeError("Invalid exception"); } using var warn = Runtime.PyObject_GetAttrString(warnings_module.obj, "warn"); Exceptions.ErrorCheck(warn.Borrow()); using var argsTemp = Runtime.PyTuple_New(3); BorrowedReference args = argsTemp.BorrowOrThrow(); using var msg = Runtime.PyString_FromString(message); Runtime.PyTuple_SetItem(args, 0, msg.StealOrThrow()); Runtime.PyTuple_SetItem(args, 1, exception); using var level = Runtime.PyInt_FromInt32(stacklevel); Runtime.PyTuple_SetItem(args, 2, level.StealOrThrow()); using var result = Runtime.PyObject_CallObject(warn.Borrow(), args); Exceptions.ErrorCheck(result.Borrow()); }
/// <remarks> /// the lines /// // XXX - hack to raise a compatible old-style exception ;( /// if (Runtime.wrap_exceptions) { /// CallOneOfTheseMethods(); /// /// </remarks> internal static void SetupExceptionHack() { ns_exc = ClassManager.GetClass(typeof(Exception)).pyHandle; cache = new Hashtable(); string code = "import exceptions\n" + "class Exception(exceptions.Exception):\n" + " _class = None\n" + " _inner = None\n" + " \n" + " #@property\n" + " def message(self):\n" + " return self.Message\n" + " message = property(message)\n" + " \n" + " def __init__(self, *args, **kw):\n" + " inst = self.__class__._class(*args, **kw)\n" + " self.__dict__['_inner'] = inst\n" + " exceptions.Exception.__init__(self, *args, **kw)\n" + "\n" + " def __getattr__(self, name, _marker=[]):\n" + " inner = self.__dict__['_inner']\n" + " v = getattr(inner, name, _marker)\n" + " if v is not _marker:\n" + " return v\n" + " v = self.__dict__.get(name, _marker)\n" + " if v is not _marker:\n" + " return v\n" + " raise AttributeError(name)\n" + "\n" + " def __setattr__(self, name, value):\n" + " inner = self.__dict__['_inner']\n" + " setattr(inner, name, value)\n" + "\n" + " def __str__(self):\n" + " inner = self.__dict__.get('_inner')\n" + " msg = getattr(inner, 'Message', '')\n" + " st = getattr(inner, 'StackTrace', '')\n" + " st = st and '\\n' + st or ''\n" + " return msg + st\n" + " \n" + " def __repr__(self):\n" + " inner = self.__dict__.get('_inner')\n" + " msg = getattr(inner, 'Message', '')\n" + " name = self.__class__.__name__\n" + " return '%s(\\'%s\\',)' % (name, msg) \n" + "\n"; IntPtr dict = Runtime.PyDict_New(); IntPtr builtins = Runtime.PyEval_GetBuiltins(); Runtime.PyDict_SetItemString(dict, "__builtins__", builtins); IntPtr namestr = Runtime.PyString_FromString("System"); Runtime.PyDict_SetItemString(dict, "__name__", namestr); Runtime.Decref(namestr); Runtime.PyDict_SetItemString(dict, "__file__", Runtime.PyNone); Runtime.PyDict_SetItemString(dict, "__doc__", Runtime.PyNone); IntPtr flag = Runtime.Py_file_input; IntPtr result = Runtime.PyRun_String(code, flag, dict, dict); Exceptions.ErrorCheck(result); Runtime.Decref(result); os_exc = Runtime.PyDict_GetItemString(dict, "Exception"); Runtime.PyObject_SetAttrString(os_exc, "_class", ns_exc); Runtime.PyErr_Clear(); }