【发布时间】:2017-05-07 22:02:20
【问题描述】:
我已经编写了一个 python 脚本来解析一个 xml 文件。我从 C# 项目中调用这个文件。但是在运行程序时出现错误:没有名为 xml.etree.cElementTree 的模块。
Program.cs
-----------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IronPython.Hosting;
using IronPython.Modules;
namespace RunExternalScript
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press enter to execute the python script!");
Console.ReadLine();
var py = Python.CreateEngine();
try
{
py.ExecuteFile("wg.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();
}
}
}
wg.py
-----
import xml.etree.cElementTree as ET
tree = ET.parse('Wg.xml')
root = tree.getroot()
childrens = root.getchildren()
for p in root.findall('WGTemplate'):
name = p.find('TemplateName').text
# print(name)
loc = p.find('Filename').text
# print(loc)
for p1 in p.findall('Product'):
print("{:<50}{:<50}{:>50}".format(name, loc, p1.text))
注意:没有名为“xml”的文件夹或文件
【问题讨论】:
-
脚本在独立运行时是否有效?
-
是的。它运行良好。唯一的挑战是与 c# 集成时。
-
是否有任何标准库模块可以工作,还是与 etree 隔离?查看this answer,了解您需要如何为托管的 python 引擎提供有关标准运行时位置的信息。
-
Microsoft.Dynamic.dll 中出现“IronPython.Runtime.Exceptions.ImportException”类型的未处理异常附加信息:无法从 xml.etree 导入 cElementTree
-
点击您上面发布的链接后将引发上述异常。
标签: c# xml python-2.7 parsing ironpython