【Python自动化运维之路Day7】基础篇

今日目录:

模块

configparser

xml

shutil

zipfile

tarfile

subprocess

面向对象(上)

一. 模块

上一期博客里列出了几个常用模块(os,hashlib,sys,re), 还有几个剩余的,这篇来继续往下走。

1. configparser模块

configparser模块是Python自带模块,主要用于处理特定的文件(ini文件),格式比较像MySQL的配置文件类型,就是文件中有多个section,每个section下面有多个配置项,如下:

[mysqld]
basedir = /usr/local/mysql
datadir = /data/mysql
socket = /data/mysql/mysql.sock

[client]
host = localhost
port = 3306
socket = /data/mysql/mysqld.sock

假定配置文件名字是 my.cnf

(1)获取所有节点(section):使用sections() 方法

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

import configparser

config = configparser.ConfigParser()   #先把config应用一下configparser,个人感觉有点像logging模块中的logger一样
config.read(‘my.cnf‘,encoding=‘utf-8‘)  #读取配置文件,编码类型为utf-8

result = config.sections() #使用sections()方法读取所有section,以列表形式返回
print(result)

#结果
[‘mysqld‘, ‘client‘]

(2)获取指定section下所有键值对:items()方法

import configparser

config = configparser.ConfigParser()
config.read(‘my.cnf‘,encoding=‘utf-8‘)

#使用items() 方法列出指定section下所有的键值对,返回一个列表的形式,key和value列表中的一个tuple
result = config.items(‘mysqld‘)
print(result)

#结果:
[(‘basedir‘, ‘/usr/local/mysql‘), (‘datadir‘, ‘/data/mysql‘), (‘socket‘, ‘/data/mysql/mysql.sock‘)]

(3)获取指定节点下所有的键, 使用options() 方法

import configparser

config = configparser.ConfigParser()
config.read(‘my.cnf‘,encoding=‘utf-8‘)

#获取指定section下的所有的键,以列表的形式返回
result = config.options(‘mysqld‘)
print(result)

#结果:
[‘basedir‘, ‘datadir‘, ‘socket‘]

(4)获取指定节点下键的值, 使用get() 方法

import configparser

config = configparser.ConfigParser()
config.read(‘my.cnf‘,encoding=‘utf-8‘)
#get方法,mysqld节点下socket键
result = config.get(‘mysqld‘,‘socket‘)
print(result)

#执行结果:
/data/mysql/mysql.sock

(5)检查、删除、添加特定section,方法has_section(), add_section(), remove_section()

import configparser

config = configparser.ConfigParser()
config.read(‘my.cnf‘,encoding=‘utf-8‘)

#检查指定的section是否存在,返回一个布尔值,存在为True
result = config.has_section(‘mysqld‘)

print(result)
#结果: True

#######################################
#添加节点 mysqldump
config.add_section(‘mysqldump‘)
config.write(open(‘my.cnf‘,‘w‘))  #需要使用write方法写入内存数据到配置文件中,不然是不能持久化到文件的
result = config.sections()
print(result)

#执行sections查看添加后结果:
[‘mysqld‘, ‘client‘, ‘mysqldump‘]

#######################################
#删除节点,mysqldump
config.remove_section(‘mysqldump‘)  #使用remove()方法
config.write(open(‘my.cnf‘,‘w‘))  #同样默认是在内存中操作,需要调用write方法,将内存数据写入到文件来持久化存储
result = config.sections()
print(result)

#执行sections查看添加后结果:
[‘mysqld‘, ‘client‘ ]

(6) 检查、删除设置section内的key-value

#检查section mysqld下的socket键值对是否存在
import configparser

config = configparser.ConfigParser()
config.read(‘my.cnf‘,encoding=‘utf-8‘)
#使用has_option方法,返回一个布尔值,存在为True
result = config.has_option(‘mysqld‘,‘socket‘)
print(result)
#执行结果:
True

#####################################
#在mysqld中添加 键 innodb_file_per_table 值为1
#使用set方法
config.set(‘mysqld‘,‘innodb_file_per_table‘,‘1‘)
config.write(open(‘my.cnf‘,‘w‘))  #同样需要写入内存数据到文件,使用write方法
result = config.options(‘mysqld‘)
print(result)

#执行查看结果:
[‘basedir‘, ‘datadir‘, ‘socket‘, ‘innodb_file_per_table‘]

#####################################
#删除mysqld下的socket键
#使用remove_option()方法
config.remove_option(‘mysqld‘,‘innodb_file_per_table‘)
config.write(open(‘my.cnf‘,‘w‘))  #写入内存数据到文件
result = config.options(‘mysqld‘)
print(result)

#执行查看结果:
[‘basedir‘, ‘datadir‘, ‘socket‘]

使用configparser可以方便的对配置文件(ini)进行操作,其实configparser底层也是使用open函数打开文件,然后在此基础上做操作。

2. xml模块

xml在Internet上被广泛的用于数据交换,同时xml也是一种存储应用数据的常用格式。如下xml例子:

<?xml version="1.0"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
    <channel>
        <title>Planet Python</title>
        <link>http://planet.python.org/</link>
        <language>en</language>
        <description>Planet Python - http://planet.python.org/</description>
        <item>
            <title>Steve Holden: Python for Data Analysis</title>
            <guid>http://holdenweb.blogspot.com/...-data-analysis.html</guid>
            <link>http://holdenweb.blogspot.com/...-data-analysis.html</link>
            <description>...</description>
            <pubDate>Mon, 19 Nov 2012 02:13:51 +0000</pubDate>
        </item>
        <item>
            <title>Vasudev Ram: The Python Data model (for v2 and v3)</title>
            <guid>http://jugad2.blogspot.com/...-data-model.html</guid>
            <link>http://jugad2.blogspot.com/...-data-model.html</link>
            <description>...</description>
            <pubDate>Sun, 18 Nov 2012 22:06:47 +0000</pubDate>
        </item>
        <item>
            <title>Python Diary: Been playing around with Object Databases</title>
            <guid>http://www.pythondiary.com/...-object-databases.html</guid>
            <link>http://www.pythondiary.com/...-object-databases.html</link>
            <description>...</description>
            <pubDate>Sun, 18 Nov 2012 20:40:29 +0000</pubDate>
        </item>
        ...
    </channel>
</rss>

(1) 解析xml

使用XML() 将字符串解析成xml对象

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

from xml.etree import ElementTree as ET

#打开文件
result_xml = open(‘example.xml‘,‘r‘).read()
#将字符串解析成xml特殊对象,root指的是xml文件的根节点
root = ET.XML(result_xml)
print(root)
#结果, 返回一个Element对象
<Element ‘rss‘ at 0x1018772c8>

使用xml.etree.ElementTree.parse()  函数解析整个xml文件并将其转换成一个文档对象。

tree = ET.parse(‘example.xml‘)
root = tree.getroot()
print(root)

#执行后结果:
<Element ‘rss‘ at 0x1019772c8>

(2)操作xml

xml格式类型是节点里嵌套节点 ,所以对于每一个节点都有如下的功能:

class Element:
    """An XML element.

    This class is the reference implementation of the Element interface.

    An element‘s length is its number of subelements.  That means if you
    want to check if an element is truly empty, you should check BOTH
    its length AND its text attribute.

    The element tag, attribute names, and attribute values can be either
    bytes or strings.

    *tag* is the element name.  *attrib* is an optional dictionary containing
    element attributes. *extra* are additional element attributes given as
    keyword arguments.

    Example form:
        <tag attrib>text<child/>...</tag>tail

    """

    当前节点的标签名
    tag = None
    """The element‘s name."""

    当前节点的属性

    attrib = None
    """Dictionary of the element‘s attributes."""

    当前节点的内容
    text = None
    """
    Text before first subelement. This is either a string or the value None.
    Note that if there is no text, this attribute may be either
    None or the empty string, depending on the parser.

    """

    tail = None
    """
    Text after this element‘s end tag, but before the next sibling element‘s
    start tag.  This is either a string or the value None.  Note that if there
    was no text, this attribute may be either None or an empty string,
    depending on the parser.

    """

    def __init__(self, tag, attrib={}, **extra):
        if not isinstance(attrib, dict):
            raise TypeError("attrib must be dict, not %s" % (
                attrib.__class__.__name__,))
        attrib = attrib.copy()
        attrib.update(extra)
        self.tag = tag
        self.attrib = attrib
        self._children = []

    def __repr__(self):
        return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))

    def makeelement(self, tag, attrib):
        创建一个新节点
        """Create a new element with the same type.

        *tag* is a string containing the element name.
        *attrib* is a dictionary containing the element attributes.

        Do not call this method, use the SubElement factory function instead.

        """
        return self.__class__(tag, attrib)

    def copy(self):
        """Return copy of current element.

        This creates a shallow copy. Subelements will be shared with the
        original tree.

        """
        elem = self.makeelement(self.tag, self.attrib)
        elem.text = self.text
        elem.tail = self.tail
        elem[:] = self
        return elem

    def __len__(self):
        return len(self._children)

    def __bool__(self):
        warnings.warn(
            "The behavior of this method will change in future versions.  "
            "Use specific ‘len(elem)‘ or ‘elem is not None‘ test instead.",
            FutureWarning, stacklevel=2
            )
        return len(self._children) != 0 # emulate old behaviour, for now

    def __getitem__(self, index):
        return self._children[index]

    def __setitem__(self, index, element):
        # if isinstance(index, slice):
        #     for elt in element:
        #         assert iselement(elt)
        # else:
        #     assert iselement(element)
        self._children[index] = element

    def __delitem__(self, index):
        del self._children[index]

    def append(self, subelement):
        为当前节点追加一个子节点
        """Add *subelement* to the end of this element.

        The new element will appear in document order after the last existing
        subelement (or directly after the text, if it‘s the first subelement),
        but before the end tag for this element.

        """
        self._assert_is_element(subelement)
        self._children.append(subelement)

    def extend(self, elements):
        为当前节点扩展 n 个子节点
        """Append subelements from a sequence.

        *elements* is a sequence with zero or more elements.

        """
        for element in elements:
            self._assert_is_element(element)
        self._children.extend(elements)

    def insert(self, index, subelement):
        在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置
        """Insert *subelement* at position *index*."""
        self._assert_is_element(subelement)
        self._children.insert(index, subelement)

    def _assert_is_element(self, e):
        # Need to refer to the actual Python implementation, not the
        # shadowing C implementation.
        if not isinstance(e, _Element_Py):
            raise TypeError(‘expected an Element, not %s‘ % type(e).__name__)

    def remove(self, subelement):
        在当前节点在子节点中删除某个节点
        """Remove matching subelement.

        Unlike the find methods, this method compares elements based on
        identity, NOT ON tag value or contents.  To remove subelements by
        other means, the easiest way is to use a list comprehension to
        select what elements to keep, and then use slice assignment to update
        the parent element.

        ValueError is raised if a matching element could not be found.

        """
        # assert iselement(element)
        self._children.remove(subelement)

    def getchildren(self):
        获取所有的子节点(废弃)
        """(Deprecated) Return all subelements.

        Elements are returned in document order.

        """
        warnings.warn(
            "This method will be removed in future versions.  "
            "Use ‘list(elem)‘ or iteration over elem instead.",
            DeprecationWarning, stacklevel=2
            )
        return self._children

    def find(self, path, namespaces=None):
        获取第一个寻找到的子节点
        """Find first matching element by tag name or path.

        *path* is a string having either an element tag or an XPath,
        *namespaces* is an optional mapping from namespace prefix to full name.

        Return the first matching element, or None if no element was found.

        """
        return ElementPath.find(self, path, namespaces)

    def findtext(self, path, default=None, namespaces=None):
        获取第一个寻找到的子节点的内容
        """Find text for first matching element by tag name or path.

        *path* is a string having either an element tag or an XPath,
        *default* is the value to return if the element was not found,
        *namespaces* is an optional mapping from namespace prefix to full name.

        Return text content of first matching element, or default value if
        none was found.  Note that if an element is found having no text
        content, the empty string is returned.

        """
        return ElementPath.findtext(self, path, default, namespaces)

    def findall(self, path, namespaces=None):
        获取所有的子节点
        """Find all matching subelements by tag name or path.

        *path* is a string having either an element tag or an XPath,
        *namespaces* is an optional mapping from namespace prefix to full name.

        Returns list containing all matching elements in document order.

        """
        return ElementPath.findall(self, path, namespaces)

    def iterfind(self, path, namespaces=None):
        获取所有指定的节点,并创建一个迭代器(可以被for循环)
        """Find all matching subelements by tag name or path.

        *path* is a string having either an element tag or an XPath,
        *namespaces* is an optional mapping from namespace prefix to full name.

        Return an iterable yielding all matching elements in document order.

        """
        return ElementPath.iterfind(self, path, namespaces)

    def clear(self):
        清空节点
        """Reset element.

        This function removes all subelements, clears all attributes, and sets
        the text and tail attributes to None.

        """
        self.attrib.clear()
        self._children = []
        self.text = self.tail = None

    def get(self, key, default=None):
        获取当前节点的属性值
        """Get element attribute.

        Equivalent to attrib.get, but some implementations may handle this a
        bit more efficiently.  *key* is what attribute to look for, and
        *default* is what to return if the attribute was not found.

        Returns a string containing the attribute value, or the default if
        attribute was not found.

        """
        return self.attrib.get(key, default)

    def set(self, key, value):
        为当前节点设置属性值
        """Set element attribute.

        Equivalent to attrib[key] = value, but some implementations may handle
        this a bit more efficiently.  *key* is what attribute to set, and
        *value* is the attribute value to set it to.

        """
        self.attrib[key] = value

    def keys(self):
        获取当前节点的所有属性的 key

        """Get list of attribute names.

        Names are returned in an arbitrary order, just like an ordinary
        Python dict.  Equivalent to attrib.keys()

        """
        return self.attrib.keys()

    def items(self):
        获取当前节点的所有属性值,每个属性都是一个键值对
        """Get element attributes as a sequence.

        The attributes are returned in arbitrary order.  Equivalent to
        attrib.items().

        Return a list of (name, value) tuples.

        """
        return self.attrib.items()

    def iter(self, tag=None):
        在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。
        """Create tree iterator.

        The iterator loops over the element and all subelements in document
        order, returning all elements with a matching tag.

        If the tree structure is modified during iteration, new or removed
        elements may or may not be included.  To get a stable set, use the
        list() function on the iterator, and loop over the resulting list.

        *tag* is what tags to look for (default is to return all elements)

        Return an iterator containing all the matching elements.

        """
        if tag == "*":
            tag = None
        if tag is None or self.tag == tag:
            yield self
        for e in self._children:
            yield from e.iter(tag)

    # compatibility
    def getiterator(self, tag=None):
        # Change for a DeprecationWarning in 1.4
        warnings.warn(
            "This method will be removed in future versions.  "
            "Use ‘elem.iter()‘ or ‘list(elem.iter())‘ instead.",
            PendingDeprecationWarning, stacklevel=2
        )
        return list(self.iter(tag))

    def itertext(self):
        在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。
        """Create text iterator.

        The iterator loops over the element and all subelements in document
        order, returning all inner text.

        """
        tag = self.tag
        if not isinstance(tag, str) and tag is not None:
            return
        if self.text:
            yield self.text
        for e in self:
            yield from e.itertext()
            if e.tail:
                yield e.tail

节点功能

遍历xml文档的所有内容:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

from xml.etree import ElementTree as ET

# 解析xml字符串
# result_xml = open(‘example.xml‘,‘r‘).read()
# root = ET.XML(result_xml)

#直接对解析xml文档
tree = ET.parse(‘example.xml‘)
#获取根节点
root = tree.getroot()

#操作
#获取顶级标签
print(root.tag)

#遍历xml文档的第二层
for i in root:
    print(i.tag,i.attrib)
    #循环遍历第三层
    for j in i:
        print(j.tag,j.attrib)
        #第四层的标签和内容
        for c in j:
            print(c.tag,c.text)

遍历xml文档的所有内容

遍历xml文档中指定的节点:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

from xml.etree import ElementTree as ET

# 解析xml字符串
# result_xml = open(‘example.xml‘,‘r‘).read()
# root = ET.XML(result_xml)

#直接对解析xml文档
tree = ET.parse(‘example.xml‘)
#获取根节点
root = tree.getroot()

#操作
#获取顶级标签
print(root.tag)

#遍历xml文档的第二层
for i in root:
    print(i.tag,i.attrib)
# 遍历所有的link节点,打印标签和内容,内容用text()
    for j in i.iter(‘link‘):
        print(j.tag,j.text)

#执行结果如下:
rss
channel {}
link http://planet.python.org/
link http://holdenweb.blogspot.com/...-data-analysis.html
link http://jugad2.blogspot.com/...-data-model.html
link http://www.pythondiary.com/...-object-databases.html

遍历xml文档中指定节点link内容

修改节点的内容

和上面configparser一样,所做的修改是在内存中进行,并不会对xml原始文档做修改,如果需要保存修改的配置,需要将内存里的数据写入到xml文件中。

也是分两种方式,解析字符串方式的修改保存, 和直接解析文件方式的修改,保存。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

from xml.etree import ElementTree as ET

# 解析xml字符串
result_xml = open(‘example.xml‘,‘r‘).read()
#找到根节点
root = ET.XML(result_xml)

#顶级标签
print(‘顶级标签: %s‘%root.tag)

#循环所有的‘link‘节点

for i in root:
    for j in i.iter(‘item‘):
        #修改原有属性:
        j.text = str(‘http://www.jd.com‘)

        #添加属性:
        j.set(‘linkA‘,‘https://www.dbq168.com‘)
        j.set(‘linkB‘,‘http://www.sina.com.cn‘)

        #删除原有属性:
        del j.attrib[‘linkB‘]
        print(type(j.attrib))
        print(j.attrib)
#保存内存中的修改到一个新文件,example_new.xml
tree = ET.ElementTree(root)
tree.write(‘example_new.xlm‘,encoding=‘utf-8‘)

解析字符串方式修改保存

# #直接对解析xml文档
tree = ET.parse(‘example.xml‘)
#获取根节点
root = tree.getroot()

#顶级标签
print(‘顶级标签: %s‘%root.tag)

for i in root:
    for j in i.iter(‘item‘):
        #修改原有属性:
        j.text = str(‘http://www.jd.com‘)

        #添加属性:
        j.set(‘linkA‘,‘https://www.dbq168.com‘)
        j.set(‘linkB‘,‘http://www.sina.com.cn‘)

        #删除原有属性:
        del j.attrib[‘linkB‘]
        print(type(j.attrib))
        print(j.attrib)

#保存文件到example_new2.xml
tree.write(‘example_new2.xml‘,encoding=‘utf-8‘)

解析xml文件方式修改保存

删除节点,删除所有节点下的language

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

from xml.etree import ElementTree as ET

# 解析xml字符串
result_xml = open(‘example.xml‘,‘r‘).read()
#找到根节点
root = ET.XML(result_xml)

#顶级标签
print(‘顶级标签: %s‘%root.tag)

#遍历
for i in root:
    for j in i.findall(‘language‘):
        i.remove(j)

#保存文件:
tree = ET.ElementTree(root)
tree.write(‘example_new.xml‘,encoding=‘utf-8‘)

解析字符串方式删除节点,保存配置

from xml.etree import ElementTree as ET
# #直接对解析xml文档
tree = ET.parse(‘example.xml‘)
#获取根节点
root = tree.getroot()

#顶级标签
print(‘顶级标签: %s‘%root.tag)

#遍历
for i in root:
    for j in i.findall(‘language‘):
        i.remove(j)

#保存文件:

tree.write(‘example_new2.xml‘,encoding=‘utf-8‘)

解析xml文件方式删除节点,保存配置

(3) 创建xml文档

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

from xml.etree import ElementTree as ET

#创建根节点
root = ET.Element(‘company‘)

#创建节点的部门
ceo = ET.Element(‘manager‘,{‘ceo‘:‘xiaomage‘})

#创建coo
coo = ET.Element(‘manager‘,{‘coo‘:‘xiaoyang‘})

#创建cto
cto = ET.Element(‘manager‘,{‘cto‘:‘laowang‘})

#给cto创建部门
dev = ET.Element(‘tech‘,{‘dev‘:‘xiaoli‘})
ops = ET.Element(‘tech‘,{‘ops‘:‘xiaoqiang‘})

cto.append(dev)
cto.append(ops)

#将manager添加到root中
root.append(ceo)
root.append(coo)
root.append(cto)

tree = ET.ElementTree(root)
tree.write(‘company.xml‘,encoding=‘utf-8‘,short_empty_elements=False)

#默认没有缩进:
<company><manager ceo="xiaomage"></manager><manager coo="xiaoyang"></manager><manager cto="laowang"><tech dev="xiaoli"></tech><tech ops="xiaoqiang"></tech></manager></company>

方式一

from xml.etree import ElementTree as ET

#创建根节点
root = ET.Element(‘company‘)

#创建高管
ceo = root.makeelement(‘manager‘,{‘ceo‘:‘xiaomage‘})
coo = root.makeelement(‘manager‘,{‘coo‘:‘xiaoyang‘})
cto = root.makeelement(‘manager‘,{‘cto‘:‘laowang‘})

#创建技术部门
dev = cto.makeelement(‘tech‘,{‘dev‘:‘xiaoli‘})
ops = cto.makeelement(‘tech‘,{‘ops‘:‘xiaoqiang‘})

cto.append(dev)
cto.append(ops)

#添加部门到根节点
root.append(ceo)
root.append(coo)
root.append(cto)

tree = ET.ElementTree(root)
tree.write(‘company_v2.xml‘,encoding=‘utf-8‘,short_empty_elements=False)

#默认没有缩进:
<company><manager ceo="xiaomage"></manager><manager coo="xiaoyang"></manager><manager cto="laowang"><tech dev="xiaoli"></tech><tech ops="xiaoqiang"></tech></manager></company>

方式二创建

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: DBQ(Du Baoqiang)

from xml.etree import ElementTree as ET

#创建根节点
root = ET.Element(‘company‘)

#创建高管
ceo = ET.SubElement(root,‘manager‘,attrib={‘ceo‘:‘xiaomage‘})
coo = ET.SubElement(root,‘manager‘,attrib={‘coo‘:‘xiaoyang‘})
cto = ET.SubElement(root,‘manager‘,attrib={‘cto‘:‘laowang‘})
#创建技术部门
dev = ET.SubElement(cto,‘tech‘,{‘dev‘:‘xiaoli‘})
ops = ET.SubElement(cto,‘tech‘,{‘ops‘:‘xiaoqiang‘})

cto.append(dev)
cto.append(ops)

tree = ET.ElementTree(root)  #生成文档对象
tree.write(‘company_v3.xml‘,encoding=‘utf-8‘,short_empty_elements=False)

# #创建根节点
# root = ET.Element(‘company‘)
#
# #创建高管
# ceo = root.makeelement(‘manager‘,{‘ceo‘:‘xiaomage‘})
# coo = root.makeelement(‘manager‘,{‘coo‘:‘xiaoyang‘})
# cto = root.makeelement(‘manager‘,{‘cto‘:‘laowang‘})
#
# #创建技术部门
# dev = cto.makeelement(‘tech‘,{‘dev‘:‘xiaoli‘})
# ops = cto.makeelement(‘tech‘,{‘ops‘:‘xiaoqiang‘})
#
# cto.append(dev)
# cto.append(ops)
#
# #添加部门到根节点
# root.append(ceo)
# root.append(coo)
# root.append(cto)
#
# tree = ET.ElementTree(root)
# tree.write(‘company_v2.xml‘,encoding=‘utf-8‘,short_empty_elements=False)

# #创建根节点
# root = ET.Element(‘company‘)
#
# #创建节点的部门
# ceo = ET.Element(‘manager‘,{‘ceo‘:‘xiaomage‘})
#
# #创建coo
# coo = ET.Element(‘manager‘,{‘coo‘:‘xiaoyang‘})
#
# #创建cto
# cto = ET.Element(‘manager‘,{‘cto‘:‘laowang‘})
#
# #给cto创建部门
# dev = ET.Element(‘tech‘,{‘dev‘:‘xiaoli‘})
# ops = ET.Element(‘tech‘,{‘ops‘:‘xiaoqiang‘})
#
# cto.append(dev)
# cto.append(ops)
#
# #将manager添加到root中
# root.append(ceo)
# root.append(coo)
# root.append(cto)
#
# tree = ET.ElementTree(root)
# tree.write(‘company.xml‘,encoding=‘utf-8‘,short_empty_elements=False)

#默认没有缩进:
<company><manager ceo="xiaomage"></manager><manager coo="xiaoyang"></manager><manager cto="laowang"><tech dev="xiaoli"></tech><tech ops="xiaoqiang"></tech><tech dev="xiaoli"></tech><tech ops="xiaoqiang"></tech></manager></company>

方式三创建

默认保存的xml没有缩进,特别的难看,可以按照下面方式添加缩进:

from xml.etree import ElementTree as ET
from xml.dom import minidom

def prettify(string):
    ‘‘‘
    将节点转换成字符串,并添加缩进
    :param string:
    :return:
    ‘‘‘
    rough_string = ET.tostring(string,‘utf-8‘)
    reparesd = minidom.parseString(rough_string)
    return reparesd.toprettyxml(indent=‘\t‘)

#创建根节点
root = ET.Element(‘company‘)

#创建节点的部门
ceo = ET.Element(‘manager‘,{‘ceo‘:‘xiaomage‘})

#创建coo
coo = ET.Element(‘manager‘,{‘coo‘:‘xiaoyang‘})

#创建cto
cto = ET.Element(‘manager‘,{‘cto‘:‘laowang‘})

#给cto创建部门
dev = ET.Element(‘tech‘,{‘dev‘:‘xiaoli‘})
ops = ET.Element(‘tech‘,{‘ops‘:‘xiaoqiang‘})

cto.append(dev)
cto.append(ops)

#将manager添加到root中
root.append(ceo)
root.append(coo)
root.append(cto)

string = prettify(root)

f = open(‘company.xml‘,‘w‘,encoding=‘utf-8‘)
f.write(string)
f.close()

#执行结果:
<?xml version="1.0" ?>
<company>
    <manager ceo="xiaomage"/>
    <manager coo="xiaoyang"/>
    <manager cto="laowang">
        <tech dev="xiaoli"/>
        <tech ops="xiaoqiang"/>
    </manager>
</company>

缩进

from xml.etree import ElementTree as ET
from xml.dom import minidom

def prettify(string):
    ‘‘‘
    将节点转换成字符串,并添加缩进
    :param string:
    :return:
    ‘‘‘
    rough_string = ET.tostring(string,‘utf-8‘)
    reparesd = minidom.parseString(rough_string)
    return reparesd.toprettyxml(indent=‘\t‘)

#创建根节点
root = ET.Element(‘company‘)

#创建高管
ceo = root.makeelement(‘manager‘,{‘ceo‘:‘xiaomage‘})
coo = root.makeelement(‘manager‘,{‘coo‘:‘xiaoyang‘})
cto = root.makeelement(‘manager‘,{‘cto‘:‘laowang‘})

#创建技术部门
dev = cto.makeelement(‘tech‘,{‘dev‘:‘xiaoli‘})
ops = cto.makeelement(‘tech‘,{‘ops‘:‘xiaoqiang‘})

cto.append(dev)
cto.append(ops)

#添加部门到根节点
root.append(ceo)
root.append(coo)
root.append(cto)

#调用函数,转下
string = prettify(root)
#而后用open函数打开,在写入转换后的
f = open(‘company_v2.xml‘,‘w‘,encoding=‘utf-8‘)
f.write(string)
f.close()

三种创建方式都一样!

(4) 命令空间

from xml.etree import ElementTree as ET
from xml.dom import minidom

def prettify(string):
    ‘‘‘
    将节点转换成字符串,并添加缩进
    :param string:
    :return:
    ‘‘‘
    rough_string = ET.tostring(string,‘utf-8‘)
    reparesd = minidom.parseString(rough_string)
    return reparesd.toprettyxml(indent=‘\t‘)

ET.register_namespace(‘com‘,‘http://www.dbq168.com‘)

#
root = ET.Element(‘{http://www.dbq168.com}STUFF‘)
body = ET.SubElement(root,‘{http://www.dbq168.com}MORE_STUFF‘, attrib={‘{http://www.dbq168.com}hhh‘:‘123‘})
body.text = ‘STUFF EVERYWHERE!‘

string = prettify(root)
f = open(‘test.xml‘,‘w‘,encoding=‘utf-8‘)
f.write(string)
f.close()

命名空间

详细介绍

未完,待续...

时间: 2024-10-17 13:55:54

【Python自动化运维之路Day7】基础篇的相关文章

python自动化运维之路~DAY7

python自动化运维之路~DAY7 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.客户端/服务器架构 C/S 架构是一种典型的两层架构,其全称是Client/Server,即客户端服务器端架构,其客户端包含一个或多个在用户的电脑上运行的程序,而服务器端有两种,一种是数据库服务器端,客户端通过数据库连接访问服务器端的数据:另一种是Socket服务器端,服务器端的程序通过Socket与客户端的程序通信. C/S 架构也可以看做是胖客户端架构.因为客户端需要实现绝大多数的业务

python自动化运维之路~DAY10

python自动化运维之路~DAY10 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.

《Python自动化运维之路》 系统基础信息模块(一)

系统性能收集模块Psutil 目录: 系统性能信息模块psutil 系统性能信息模块psutil psutil能够轻松实现获取系统运行的进程和系统利用率包括(CPU,内存,磁盘 和网络)等.主要用于系统监控.对于系统维护来说是个不错的模块. 1.模块的安装 wget https://files.pythonhosted.org/packages/14/a2/8ac7dda36eac03950ec2668ab1b466314403031c83a95c5efc81d2acf163/psutil-5.

【Python自动化运维之路Day8】基础篇之面向对象下篇

今日目录: 类成员 成员修饰符 特殊的类成员 面向对象相关联的其他知识 异常捕获与处理 设计模式之单例模式 一. 类成员 类的成员有:字段.方法和属性 关系图如下: 1. 字段: 字段分: 静态字段 普通字段 两者在定义和使用上有所区别,如下代码: class Province: contry = '中国' #静态字段,保存在类中 def __init__(self,name): self.name = name #普通字段,保存在对象中 在内存中的存储位置是不同的, 静态字段保存在类中, 而普

【Python自动化运维之路Day5】基础篇

今日目录: 多层装饰器 字符串格式化 生成器和迭代器 递归 模块 一. 多层装饰器 还是上一篇的那个例子,关于用户管理程序:登录用户管理程序,查看用户信息的时候,系统要提示登录,登录验证成功后普通用户可以查看自己信息,管理员登录后才可以进入管理界面,普通用户提示权限不足,这样一来,就可以重新写下程序,来两个装饰器来装饰: #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Author: DBQ(Du Baoqiang) #先定义一个用户字典,判断用

【Python自动化运维之路Day9】Socket

socket也可以认为是套接字是一种源IP地址和目的IP地址以及源端口号和目的端口号的组合.网络化的应用程序在开始任何通讯之前都必须要创建套接字.就像电话的插口一样,没有它就没办法通讯. socket即是一种特殊的文件,一些socket函数就是对其进行的操作(读/写IO.打开.关闭) 我们知道两个进程如果需要进行通讯最基本的一个前提能能够唯一的标示一个进程,在本地进程通讯中我们可以使用PID来唯一标示一个进程,但PID只在本地唯一,网络中的两个进程PID冲突几率很大,这时候我们需要另辟它径了,我

python自动化运维之路4

装饰器 装饰器(decorator)是一种高级Python语法.装饰器可以对一个函数.方法或者类进行加工.在Python中,我们有多种方法对函数和类进行加工,比如在Python闭包中,我们见到函数对象作为某一个函数的返回结果.相对于其它方式,装饰器语法简单,代码可读性高.因此,装饰器在Python项目中有广泛的应用. 装饰器的应用场景:饰器是一个很著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志.性能测试.事务处理等.装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大

【Python自动化运维之路Day2】

1. 常量命名规则 在Python中,会在变量命名上标明某变量是常量,通常采用全是大写的方式来标明,如: CONNECT= '127.0.0.1' PORT = '3306' 2.Python编译 python先把源码文件(.py)编译成字节码文件(.pyc) python3执行后,生成了一个__pycache__目录,pyc会在此目录下,python2执行可以看到直接生成了一个.pyc文件 pyc  与py  时间戳不同,pyc才去重新编译 3  数据 <1> str 1.str1+str2

python自动化运维之路~DAY1

刚学python,有大神给指点指点的吗? #!/usr/bin/env python#_*_coding:utf8_*_import getpass,syscount = 0match_info = False #用布尔值来标志用户密码是否匹配,默认是flasewhile count < 3: username = input("\033[32;1mAsk you for a username :\033[0m") with open("locked.txt"