Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IronPython - emit warning from C#

Tags:

c#

ironpython

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.

like image 701
Joel Rein Avatar asked Dec 31 '13 12:12

Joel Rein


1 Answers

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")
like image 56
Simon Opelt Avatar answered Nov 18 '22 22:11

Simon Opelt