1
votes

My C# code calls an IronPython script that imports two packages.

My environment is:

  • Installed IronPython 2.7.1 from GitHub.
  • Installed Enthought's Python.
  • I am using Visual Studio 2012 and C# 4.5 to develop my test project.
  • I am running on a Windows Server 2012 R2 (x64).

I have also added the following references to my project:

   IronPython
   IronPython.Modules
   Microsoft Scripting
   Microsoft.Dynamic

My C# code is:

using System;
using IronPython.Hosting;
namespace RunExternalScript {
  internal class Program {
    private static void Main() {
      var py = Python.CreateEngine();
      try {
        py.ExecuteFile("script.py");
      } catch (Exception ex) {
        Console.WriteLine("Oops! We couldn't execute the script because of an exception: " + ex.Message);
      }
      Console.WriteLine("Press enter to exit...");
      Console.ReadLine();
    }
  }
}

The Python script.py is:

import pickel
import numpy
print('Imports work.')

If I comment out the two imports, the program works. My real script needs the "pickel" and "numpy" packages.

How can I get my Python script to import these two packages?

Charles

1

1 Answers

1
votes

You can tell IronPython that where to search for packages by using PythonEngine.SetSearchPaths(...) function.

For Example

var py = Python.CreateEngine();
private List<string> m_searchPaths = new List<string>();
m_searchPaths.Add(AppDomain.CurrentDomain.BaseDirectory + @"\Lib");
m_searchPaths.Add(@"C:\Python27\lib");
// Add any other Path you want to add in search path
py.SetSearchPaths(m_searchPaths);
try
{
    py.ExecuteFile("script.py");
}
catch (Exception ex)
{
    Console.WriteLine("Oops! We couldn't execute the script because of an exception: " + ex.Message);
}