Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IronPython - "AttributeError: object has no attribute" with custom classes

This seems like there is just a simple error that I cannot figure out. I am using IronPython in a C# WPF application and am getting the following error when trying to run a function from a custom C# class:AttributeError: 'MyScriptingFunctions' object has no attribute 'Procedure'.

The python script I'm running is very simple and has two lines. Line 1 executes fine, the error occurs on line 2.

    txt.Text = "some text"
    MyFunc.Procedure(5)

MyScriptingFunctions.cs:

class MyScriptingFunctions
{
    public MyScriptingFunctions() {}

    public void Procedure(int num)
    {
        Console.WriteLine("Executing procedure " + num); 
    }
}

Here is how I setup the IronPython engine:

     private void btnRunScript_Click(object sender, RoutedEventArgs e)
     {
        MyScriptingFunctions scriptFuncs = new MyScriptingFunctions();
        ScriptEngine engine = Python.CreateEngine();
        ScriptScope scope = engine.CreateScope();

        ScriptRuntime runtime = engine.Runtime;
        runtime.LoadAssembly(typeof(String).Assembly);
        runtime.LoadAssembly(typeof(Uri).Assembly);

        //Set Variable for the python script to use
        scope.SetVariable("txt", fullReadResultsTextBox);
        scope.SetVariable("MyFunc", scriptFuncs);
        string code = this.scriptTextBox.Text;
        try
        {
            ScriptSource source = engine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
            source.Execute(scope);
        }
        catch (Exception ex)
        {
            ExceptionOperations eo;
            eo = engine.GetService<ExceptionOperations>();
            string error = eo.FormatException(ex);

            MessageBox.Show(error, "There was an Error");
            return;
        }

    }

I am simply setting two variables:txt which is of type System.Windows.Controls.TextBox, and MyFunc which is an object of my custom class MyScriptingFunctions.

What am I doing wrong and why does the python script execute the TextBox methods correctly and not my custom class's methods?

like image 803
McLovin Avatar asked Mar 24 '23 12:03

McLovin


1 Answers

The only think I can see that might be an issue, or just a copy-paste error, is that the MyScriptingFunctions in not public. That shouldn't be an issue because you're passing an instance in, not trying to import the class, but it's worth a try. Otherwise everything looks fine.

like image 156
Jeff Hardy Avatar answered Apr 06 '23 18:04

Jeff Hardy