c# - IronPython - 从 C# 发出警告

标签 c# ironpython

我正在编写一个可以使用 IronPython 编写脚本的 C# 应用程序。我希望能够从 C# 代码发出非致命的 Python 警告(可以使用常规的 Python 警告捕获系统处理)。

我在 IronPython.Modules 中找到了 PythonWarnings.warn 方法,但它需要一个 CodeContext 而我无法理解如何创建/获取其中之一。

最佳答案

当从 IronPython 调用 .NET(即 C#)时,如果被调用的代码选择接收它,CodeContext 将自动注入(inject)。假设您有如下所示的程序集、类和方法:

namespace ClassLibrary1
{
    public class Class1
    {
        public static void MyMethod(CodeContext ctx, int number, string text)
        {
            var msg = string.Format("Warning: {0} and {1} ...", number, text);
            PythonWarnings.warn(ctx, msg, null, 0);
         }
    }
}

请注意,MyMethod 接受一个 CodeContext 作为它的第一个参数,并且可以从 IronPython 中调用,只需提供最后两个参数:

import clr
clr.AddReference("ClassLibrary1")
from ClassLibrary1 import Class1

Class1.MyMethod(1234, "test")

关于c# - IronPython - 从 C# 发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20857537/

相关文章:

c# - 正则表达式奇怪

python - 加载 NLTK 感知器标记器时出现 IOError

c# - 如何使用 IronPython 中的 win32api

c# - 使用 IronRuby 或 IronPython 修改 C# 对象列表

同一台机器上的 Python 和 IronPython?

c# - 错误 :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

c# - C# 是否具有等效于 Java 静态嵌套类的功能?

c# - 延迟加载已关闭。使用 .Include() 时,子对象仍会递归加载。

c# - 如何将 ResourceDictionary 中的 SolidColorBrush 的 Color 属性绑定(bind)到 ViewModel Color 属性

sql - 使用 IronPython 在 SQL Server Analysis Services 上执行查询