Search code examples
c#pythonironpythonscriptengine

How to get all local variable names and values in C# using Python ScriptEngine?


I am using Microsoft.Scripting.Hosting.ScriptEngine and instantiate it via IronPython.Hosting.Python.CreateEngine(). I then create a Scope and execute some python code.

I now would like to gather all locally assigned variable names and their values in C#. How can I extract all variable names and values that were declared and assigned in the Python script but from C# by querying the Python ScriptEngine and Scope?

Thanks


Solution

  • You can do this via a dynamic object and reflection. This is just winged code but if you send me or host the solution I can work it out for you.

    dynamic someOject = IronPython.Hosting.Python.CreateEngine();
    
    foreach (var property in someOject.GetType().GetProperties())
         Console.WriteLine($"Property Name: {property.Name} - Property Value: {property.GetValue(someOject)}");
    

    Not sure if this is what you're looking for or not... If not please let me know so I can further assist you.