程序不会产生任何错误或输出

时间:2012-11-06 13:06:41

标签: python

我有以下Python程序:

 import xml.etree.ElementTree as ET
    import sys   

    class MyXmlParser(object):

        def __init__(self, users):
            self.doc  = ET.parse("users.xml")
            self.root = self.doc.getroot()

        def do_something(self, output = sys.stdout):
            root_new  = ET.Element("users") 
            for child in self.root:
                username             = child.attrib['username']
                password             = child.attrib['password']   
                # create "user" here
                user    = ET.SubElement(root_new, "user") 
                user.set("username",username)               
                user.set("password",password) 
                # checking attribute - skip KeyError
                try:
                    remote_access   = child.attrib['remote_access']
                    user.set("remote_access", remote_access) 
                except KeyError:
                    pass

                for g in child.findall("group"):
                    # create "group" here
                    group     = ET.SubElement(user,"group")  
                    if g.text != "lion":
                        group.text = g.text 
            tree = ET.ElementTree(root_new)
            tree.write(output)
if __name__ =='main':
    parser = MyXmlParser()
    parser.do_something()

这是我的xml:

<users>
<user username="admin"  password="admin" remote_access="yes"></user>
<user username="private_user1" password="user1" ><group>group1</group><group>group2</group></user>
<user username="private_user2" fullname="user2" password="user2"><group>group1</group><group>group2</group></user>
</users>

我在这个程序中找不到任何错误。它应该输出一些xml。但目前它没有给出任何错误或输出。我期待一些xml作为输出:(提前致谢

1 个答案:

答案 0 :(得分:1)

我将您的MyXmlParser类构造函数更改为:

    def __init__(self, users=None):
        self.doc = ET.parse("users.xml")
        self.root = self.doc.getroot()

并在课程定义后添加:

if __name__==" __main_ ":
    parser = MyXmlParser()
    parser.do_something()

得到了这一行输出:

<users><user password="admin" remote_access="yes" username="admin" /><user password="user1" username="private_user1"><group>group1</group><group>group2</group></user><user password="user2" username="private_user2"><group>group1</group><group>group2</group></user></users>