C# 导入模块中的 Ironpython 导入 csv 模块时出错

本文关键字:导入 模块 出错 csv Ironpython | 更新日期: 2023-09-27 18:34:09

我正在尝试从 C# 应用程序中执行 Python 脚本,但是当它尝试启动脚本时,我收到错误ImportException was unhandled No module name csv。 我检查了Ironpython文件夹,有一个 csv.py 文件...?

我用来调用脚本的代码:

 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);

蟒蛇文件:

#!/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"
...

C# 导入模块中的 Ironpython 导入 csv 模块时出错

您创建的 IronPython 引擎不知道它应该使用的标准库实现。您可以通过添加类似

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

可以将其指向本地安装的铁 python(如我的示例所示),也可以使用相应的 NuGet 包直接将其添加到项目中。您可能还必须将其部署到输出文件夹/安装程序/...

另请注意此答案以及此答案和评论,因为它们可能会提供更多信息。