【问题标题】:Calling python script from c# program-error: No Module named xml.etree.cElementTree从 c# 程序错误调用 python 脚本:没有名为 xml.etree.cElementTree 的模块
【发布时间】: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


【解决方案1】:

设置你的python路径,了解你的系统路径 在 .py 文件中只需键入

import sys
print(sys.path)

这样您将获得您的系统路径并在

中设置所有路径
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);

希望我的回答能帮助你解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-28
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多