开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (11)
标签 (29)
master
fix-binaryformatter-usage
compare-maybetype-by-name
python3.13
noncopyableanalyzer
null-check-before-bind
python-3.13
linting-and-formatting
gitpod
backports-2.5
improve-ci
v3.0.4
v3.0.3
v3.0.2
v3.0.1
v3.0.0-r1
v3.0.0
v3.0.0-rc6
v3.0.0-rc5
v3.0.0-rc4
v3.0.0-rc3
v3.0.0-rc2
v3.0.0-rc1
v3.0.0-a2
v3.0.0-a1
v2.5.2
v2.5.1
v2.5.0
v2.5.0-rc1
v2.4.0
v2.4.0-rc2
master
分支 (11)
标签 (29)
master
fix-binaryformatter-usage
compare-maybetype-by-name
python3.13
noncopyableanalyzer
null-check-before-bind
python-3.13
linting-and-formatting
gitpod
backports-2.5
improve-ci
v3.0.4
v3.0.3
v3.0.2
v3.0.1
v3.0.0-r1
v3.0.0
v3.0.0-rc6
v3.0.0-rc5
v3.0.0-rc4
v3.0.0-rc3
v3.0.0-rc2
v3.0.0-rc1
v3.0.0-a2
v3.0.0-a1
v2.5.2
v2.5.1
v2.5.0
v2.5.0-rc1
v2.4.0
v2.4.0-rc2
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (11)
标签 (29)
master
fix-binaryformatter-usage
compare-maybetype-by-name
python3.13
noncopyableanalyzer
null-check-before-bind
python-3.13
linting-and-formatting
gitpod
backports-2.5
improve-ci
v3.0.4
v3.0.3
v3.0.2
v3.0.1
v3.0.0-r1
v3.0.0
v3.0.0-rc6
v3.0.0-rc5
v3.0.0-rc4
v3.0.0-rc3
v3.0.0-rc2
v3.0.0-rc1
v3.0.0-a2
v3.0.0-a1
v2.5.2
v2.5.1
v2.5.0
v2.5.0-rc1
v2.4.0
v2.4.0-rc2
pythonnet
/
src
/
runtime
/
Exceptions.cs
pythonnet
/
src
/
runtime
/
Exceptions.cs
Exceptions.cs 14.74 KB
一键复制 编辑 原始数据 按行查看 历史
Victor 提交于 2024年05月11日 15:34 +08:00 . handle bad paths in sys.path (#2383)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.ExceptionServices;
namespace Python.Runtime
{
/// <summary>
/// Encapsulates the Python exception APIs.
/// </summary>
/// <remarks>
/// Readability of the Exceptions class improvements as we look toward version 2.7 ...
/// </remarks>
internal static class Exceptions
{
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
// set in Initialize
internal static PyObject warnings_module;
internal static PyObject exceptions_module;
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
/// <summary>
/// Initialization performed on startup of the Python runtime.
/// </summary>
internal static void Initialize()
{
string exceptionsModuleName = "builtins";
exceptions_module = PyModule.Import(exceptionsModuleName);
warnings_module = PyModule.Import("warnings");
Type type = typeof(Exceptions);
foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static))
{
using var op = Runtime.PyObject_GetAttrString(exceptions_module.obj, fi.Name);
if (!@op.IsNull())
{
fi.SetValue(type, op.MoveToPyObject());
}
else
{
fi.SetValue(type, null);
DebugUtil.Print($"Unknown exception: {fi.Name}");
}
}
Runtime.PyErr_Clear();
}
/// <summary>
/// Cleanup resources upon shutdown of the Python runtime.
/// </summary>
internal static void Shutdown()
{
if (Runtime.Py_IsInitialized() == 0)
{
return;
}
Type type = typeof(Exceptions);
foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static))
{
var op = (PyObject?)fi.GetValue(type);
if (op is null)
{
continue;
}
op.Dispose();
fi.SetValue(null, null);
}
exceptions_module.Dispose();
warnings_module.Dispose();
}
/// <summary>
/// Set the 'args' slot on a python exception object that wraps
/// a CLR exception. This is needed for pickling CLR exceptions as
/// BaseException_reduce will only check the slots, bypassing the
/// __getattr__ implementation, and thus dereferencing a NULL
/// pointer.
/// </summary>
internal static bool SetArgsAndCause(BorrowedReference ob, Exception e)
{
NewReference args;
if (!string.IsNullOrEmpty(e.Message))
{
args = Runtime.PyTuple_New(1);
using var msg = Runtime.PyString_FromString(e.Message);
Runtime.PyTuple_SetItem(args.Borrow(), 0, msg.StealOrThrow());
}
else
{
args = Runtime.PyTuple_New(0);
}
using (args)
{
if (Runtime.PyObject_SetAttrString(ob, "args", args.Borrow()) != 0)
{
return false;
}
}
if (e.InnerException != null)
{
// Note: For an AggregateException, InnerException is only the first of the InnerExceptions.
using var cause = CLRObject.GetReference(e.InnerException);
Runtime.PyException_SetCause(ob, cause.Steal());
}
return true;
}
/// <summary>
/// Shortcut for (pointer == NULL) -&gt; throw PythonException
/// </summary>
/// <param name="pointer">Pointer to a Python object</param>
internal static BorrowedReference ErrorCheck(BorrowedReference pointer)
{
if (pointer.IsNull)
{
throw PythonException.ThrowLastAsClrException();
}
return pointer;
}
internal static void ErrorCheck(IntPtr pointer) => ErrorCheck(new BorrowedReference(pointer));
/// <summary>
/// Shortcut for (pointer == NULL or ErrorOccurred()) -&gt; throw PythonException
/// </summary>
internal static void ErrorOccurredCheck(IntPtr pointer)
{
if (pointer == IntPtr.Zero || ErrorOccurred())
{
throw PythonException.ThrowLastAsClrException();
}
}
internal static IntPtr ErrorCheckIfNull(IntPtr pointer)
{
if (pointer == IntPtr.Zero && ErrorOccurred())
{
throw PythonException.ThrowLastAsClrException();
}
return pointer;
}
/// <summary>
/// ExceptionMatches Method
/// </summary>
/// <remarks>
/// Returns true if the current Python exception matches the given
/// Python object. This is a wrapper for PyErr_ExceptionMatches.
/// </remarks>
public static bool ExceptionMatches(BorrowedReference ob)
{
return Runtime.PyErr_ExceptionMatches(ob) != 0;
}
/// <summary>
/// Sets the current Python exception given a native string.
/// This is a wrapper for the Python PyErr_SetString call.
/// </summary>
public static void SetError(BorrowedReference type, string message)
{
Runtime.PyErr_SetString(type, message);
}
/// <summary>
/// SetError Method
/// </summary>
/// <remarks>
/// Sets the current Python exception given a Python object.
/// This is a wrapper for the Python PyErr_SetObject call.
/// </remarks>
public static void SetError(BorrowedReference type, BorrowedReference exceptionObject)
{
Runtime.PyErr_SetObject(type, exceptionObject);
}
internal const string DispatchInfoAttribute = "__dispatch_info__";
/// <summary>
/// SetError Method
/// </summary>
/// <remarks>
/// Sets the current Python exception given a CLR exception
/// object. The CLR exception instance is wrapped as a Python
/// object, allowing it to be handled naturally from Python.
/// </remarks>
public static bool SetError(Exception e)
{
Debug.Assert(e is not null);
// Because delegates allow arbitrary nesting of Python calling
// managed calling Python calling... etc. it is possible that we
// might get a managed exception raised that is a wrapper for a
// Python exception. In that case we'd rather have the real thing.
if (e is PythonException pe)
{
pe.Restore();
return true;
}
using var instance = Converter.ToPython(e);
if (instance.IsNull()) return false;
var exceptionInfo = ExceptionDispatchInfo.Capture(e);
using var pyInfo = Converter.ToPython(exceptionInfo);
if (Runtime.PyObject_SetAttrString(instance.Borrow(), DispatchInfoAttribute, pyInfo.Borrow()) != 0)
return false;
Debug.Assert(Runtime.PyObject_TypeCheck(instance.Borrow(), BaseException));
var type = Runtime.PyObject_TYPE(instance.Borrow());
Runtime.PyErr_SetObject(type, instance.Borrow());
return true;
}
/// <summary>
/// When called after SetError, sets the cause of the error.
/// </summary>
/// <param name="cause">The cause of the current error</param>
public static void SetCause(Exception cause)
{
var currentException = PythonException.FetchCurrentRaw();
currentException.Normalize();
using var causeInstance = Converter.ToPython(cause);
Runtime.PyException_SetCause(currentException.Value!.Reference, causeInstance.Steal());
currentException.Restore();
}
/// <summary>
/// ErrorOccurred Method
/// </summary>
/// <remarks>
/// Returns true if an exception occurred in the Python runtime.
/// This is a wrapper for the Python PyErr_Occurred call.
/// </remarks>
public static bool ErrorOccurred()
{
return Runtime.PyErr_Occurred() != null;
}
/// <summary>
/// Clear Method
/// </summary>
/// <remarks>
/// Clear any exception that has been set in the Python runtime.
/// </remarks>
public static void Clear()
{
Runtime.PyErr_Clear();
}
//====================================================================
// 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");
warn.BorrowOrThrow();
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);
result.BorrowOrThrow();
}
public static void warn(string message, BorrowedReference exception)
{
warn(message, exception, 1);
}
public static void deprecation(string message, int stacklevel)
{
warn(message, Exceptions.DeprecationWarning, stacklevel);
}
public static void deprecation(string message)
{
deprecation(message, 1);
}
//====================================================================
// Internal helper methods for common error handling scenarios.
//====================================================================
/// <summary>
/// Raises a <see cref="TypeError"/> and attaches any existing exception as its cause.
/// </summary>
/// <param name="message">The exception message</param>
/// <returns><c>null</c></returns>
internal static NewReference RaiseTypeError(string message)
{
var cause = PythonException.FetchCurrentOrNullRaw();
cause?.Normalize();
Exceptions.SetError(Exceptions.TypeError, message);
if (cause is null) return default;
var typeError = PythonException.FetchCurrentRaw();
typeError.Normalize();
Runtime.PyException_SetCause(
typeError.Value!,
new NewReference(cause.Value!).Steal());
typeError.Restore();
return default;
}
// 2010年11月16日: Arranged in python (2.6 & 2.7) source header file order
/* Predefined exceptions are
public static variables on the Exceptions class filled in from
the python class using reflection in Initialize() looked up by
name, not position. */
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
// set in Initialize
public static PyObject BaseException;
public static PyObject Exception;
public static PyObject StopIteration;
public static PyObject GeneratorExit;
public static PyObject ArithmeticError;
public static PyObject LookupError;
public static PyObject AssertionError;
public static PyObject AttributeError;
public static PyObject BufferError;
public static PyObject EOFError;
public static PyObject FloatingPointError;
public static PyObject EnvironmentError;
public static PyObject IOError;
public static PyObject OSError;
public static PyObject ImportError;
public static PyObject ModuleNotFoundError;
public static PyObject IndexError;
public static PyObject KeyError;
public static PyObject KeyboardInterrupt;
public static PyObject MemoryError;
public static PyObject NameError;
public static PyObject OverflowError;
public static PyObject RuntimeError;
public static PyObject NotImplementedError;
public static PyObject SyntaxError;
public static PyObject IndentationError;
public static PyObject TabError;
public static PyObject ReferenceError;
public static PyObject SystemError;
public static PyObject SystemExit;
public static PyObject TypeError;
public static PyObject UnboundLocalError;
public static PyObject UnicodeError;
public static PyObject UnicodeEncodeError;
public static PyObject UnicodeDecodeError;
public static PyObject UnicodeTranslateError;
public static PyObject ValueError;
public static PyObject ZeroDivisionError;
//#ifdef MS_WINDOWS
//public static IntPtr WindowsError;
//#endif
//#ifdef __VMS
//public static IntPtr VMSError;
//#endif
//PyAPI_DATA(PyObject *) PyExc_BufferError;
//PyAPI_DATA(PyObject *) PyExc_MemoryErrorInst;
//PyAPI_DATA(PyObject *) PyExc_RecursionErrorInst;
/* Predefined warning categories */
public static PyObject Warning;
public static PyObject UserWarning;
public static PyObject DeprecationWarning;
public static PyObject PendingDeprecationWarning;
public static PyObject SyntaxWarning;
public static PyObject RuntimeWarning;
public static PyObject FutureWarning;
public static PyObject ImportWarning;
public static PyObject UnicodeWarning;
//PyAPI_DATA(PyObject *) PyExc_BytesWarning;
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
}
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/MicroDistanceStudio/pythonnet.git
git@gitee.com:MicroDistanceStudio/pythonnet.git
MicroDistanceStudio
pythonnet
pythonnet
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /