3

I have written a python script to parse a xml file. I'm calling this file from C# project. But when running a program I'm getting error: No Module named 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))

Note: There is no folder or file with name 'xml'

6
  • does the script work when run in standalone? Commented Dec 22, 2016 at 10:03
  • Yes. It works well.Only challenge is when integrated with c#.
    – meshsf
    Commented Dec 22, 2016 at 10:07
  • Does any standard library module work or is it isolated to etree? Have a look at this answer to see how you need to provide the hosted python engine with info about the location of the standard runtime. Commented Dec 22, 2016 at 10:21
  • An unhandled exception of type 'IronPython.Runtime.Exceptions.ImportException' occurred in Microsoft.Dynamic.dll Additional information: cannot import cElementTree from xml.etree
    – meshsf
    Commented Dec 23, 2016 at 8:42
  • The above exception will be thrown after following the link which you have posted above.
    – meshsf
    Commented Dec 23, 2016 at 8:44

1 Answer 1

0

set your python path, to know your system path in .py file just type

import sys
print(sys.path)

and with this you will get your sys path and set those all path in

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

i hope my answer help you to solve your problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.