从c#调用python脚本程序错误:没有名为xml.etree.cElementTree的模块

问题描述 投票:3回答:1

我编写了一个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# xml python-2.7 parsing ironpython
1个回答
0
投票

设置你的python路径,知道.py文件中的系统路径只需键入

import sys
print(sys.path)

通过这个,您将获得您的sys路径并设置所有路径

ScriptEngine engine = Python.CreateEngine(); //For Engine to initiate the script
            List<string> pathes = engine.GetSearchPaths().ToList();
            pathes.AddRange(new[]
            {
             @"<add your all path here>"
             });
            engine.SetSearchPaths(pathes);

我希望我的回答可以帮助您解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.