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"
...

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
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...
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.