IronPython - 从C#发出警告

6
我正在编写一款使用IronPython脚本的C#应用程序。我希望能够从C#代码中发出非致命的Python警告(可以使用常规的Python警告捕获系统进行处理)。
我在IronPython.Modules中找到了PythonWarnings.warn方法,但它需要一个CodeContext,我无法创建或获取其中之一。
1个回答

7
当从IronPython调用.NET(即C#)时,如果被调用的代码选择接收CodeContext,则CodeContext将自动注入。假设您有一个如下所示的程序集、类和方法:
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")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接