IronPython - emit warning from C#
Asked Answered
S

1

6

I'm writing a C# application that can be scripted using IronPython. I'd like to be able to emit non-fatal Python warnings from C# code (that can be handled using the regular Python warning-catching system).

I've found the PythonWarnings.warn method in IronPython.Modules, but it requires a CodeContext and I can't figure out how to create/get one of those.

Sorrento answered 31/12, 2013 at 12:38 Comment(0)
G
7

When .NET (i.e. C#) is invoked from IronPython the CodeContext is automatically injected if the called code opts to receive it. Assuming that you have an assembly, class, and method looking as follows:

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);
         }
    }
}

Note that MyMethod accepts a CodeContext as its first parameter and can be invoked from IronPython with just the last two parameters provided:

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

Class1.MyMethod(1234, "test")
Grebe answered 2/1, 2014 at 22:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.