2

I'm trying to execute a Python script from within a C# application but when it tries to launch the script, I receive the error ImportException was unhandled No module name csv. I checked the Ironpython folder and there is a csv.py file...?

Code I'm using to call the script:

 IDictionary<string, object> options = new Dictionary<string, object>();
 options["Argument"] = new[] { filePath, profile };
 var pyEngine = Python.CreateEngine(options);
 var pyScope = pyEngine.CreateScope();
 string script = "xccdf-xml2tsv.py";
 pyScope.SetVariable(profile, options);

 pyEngine.ExecuteFile(script, pyScope);

python file:

#!/usr/bin/env python

###
# (C) 2010 Adam Crosby
# Licensed under:
#  http://creativecommons.org/licenses/by-nc-sa/3.0/
##
import csv
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import xml.etree.ElementTree as ET
xmlns = "http://checklists.nist.gov/xccdf/1.1"
...
Chris
  • 934
  • 1
  • 17
  • 38

1 Answers1

3

The IronPython engine you created is unaware of the standard library implementation it should use. You can specify it by adding something like

var paths = pyEngine.GetSearchPaths();
paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib");
pyEngine.SetSearchPaths(paths); 

You could either point it to a locally installed iron python (as in my example) or use the appropriate NuGet package to directly add it to your project. You might also have to deploy it to your output folder/installer/...

Please also take note of this answer as well as this answer and comments as they might provide additional information.

Community
  • 1
  • 1
Simon Opelt
  • 6,136
  • 2
  • 35
  • 66
  • Thanks, I had actually read both of those other posts already, just didn't realize the answer was right there. Does an app using IronPython require users to have it installed? – Chris Dec 15 '14 at 12:07
  • 1
    You can ship the required (subset of the) standard library with your application. So it depends on how you plan to roll out/deploy your application. You could for example have the core standard library as well as csv as a local copy within your project and ship that or bake it into your exe. – Simon Opelt Dec 15 '14 at 12:10
  • I installed the Nuget package but that did not solve the problem; I ended up with the code you have above. Seems like it will be a problem for users who don't have IronPython installed though... – Chris Dec 15 '14 at 12:26
  • 2
    You have to make sure the NuGet StdLib is copied with your app, and that the proper final location is added to the search path. – Jeff Hardy Dec 15 '14 at 13:45