IronPython C# Integration
4. Importing Modules
Earlier in this tutorial we saw how Python scripts can use the Python import statement as any regular Python script can do as long as the search paths are setup correctly. Here we present another interesting approach which is to import the module from the C# code instead of the Python code.
The static IronPython.Hosting.Python.ImportModule function can be used to import a module. It returns an instance of the ScriptScope class containing all the variables from the imported module. The ScriptScope class was explained on the previous page. For instance you can use the returned scope and pass it to the ScriptSource.Execute function to execute another Python script that can use the functionality of the imported module or even use it to execute the Python methods directly from C# as we'll show in the example below.
The ImportModule function looks for the module in the search paths as a Python import statement would do so it is important the paths are setup correctly or the module won't be found.
The following example shows how a function defined in a Python module can be executed as if it were a C# function. The full example is available from our GitHub repository: IronPython/CSharpIntegration/ImportModule1