IronPython C# Integration

3 - Sharing Variables


The Microsoft.Scripting.Hosting.ScriptScope class is used to hold the list of variables that are currently in scope and their associated values. The ScriptScope class provides methods to set, get and remove variables from the scope. They are SetVariable, GetVariable and RemoveVariable. To get the list of all variables in the scope use the GetVariableNames method.

In our examples on page 1 we used pythonScript.Execute(); to run the scripts. The parameter-less Execute() function creates a ScriptScope instance internally so it is not accessible to the caller. We can however use other overloads to create the ScriptScope ourselves and pass it to the

The following example shows how these functions can be used. The full example is available from our GitHub repository: IronPythonTutorials/CSharpIntegration/PythonScriptExecution5.

 File: Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PythonScriptExecution5
    class Program
        static void Main(string[] args)
            Microsoft.Scripting.Hosting.ScriptEngine pythonEngine = IronPython.Hosting.Python.CreateEngine();
            Microsoft.Scripting.Hosting.ScriptSource pythonScript = pythonEngine.CreateScriptSourceFromString(
                "helloWorldString = 'Hello World!'\n" +
                "print helloWorldString\n" +
                "print externalString"

            Microsoft.Scripting.Hosting.ScriptScope scope = pythonEngine.CreateScope();
            scope.SetVariable("externalString", "How do you do?");


            System.Console.Out.WriteLine("List of variables in the scope:");
            foreach (string name in scope.GetVariableNames())
                System.Console.Out.Write(name + " ");

            System.Console.Out.WriteLine("Variable values:");
            System.Console.Out.WriteLine("helloWorldString: " + scope.GetVariable("helloWorldString"));
            System.Console.Out.WriteLine("externalString: " + scope.GetVariable("externalString"));      

In this example the script defines the helloWorldString variable and uses a variable called externalString that is not defined in the script. It then prints both variables.

The externalString variable shows how the C# code can use the SetVariable method to add variables to the scope that can then be used by the script.

After the script is executed the scope contains the list of variables that were added by the script. The C# code uses the various functions we mentioned before to print what is in the scope after execution.