Python 面向对象及configparser模块。。。

概述

  • 面向过程:根据业务逻辑从上到下写垒代码
  • 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
  • 面向对象:对函数进行分类和封装,让开发“更快更好更强...”

面向对象编程(Object Oriented Programming,OOP,面向对象程序设计)

# 函数式编程
def mail(email, message):
    print(email, message)
    print("发送邮件")
    return True

mail("rain@163.com", '测试函数')
# rain@163.com 测试函数
# 发送邮件
# 面向对象: 类, 对象
class Foo:
    # 方法
    def mail(self, email, message):
        print(email, message)
        print("发送邮件")
        return True

# 调用
# 1、创建对象 类名()
obj = Foo()
# 2、通过对象去执行方法
obj.mail("rain@163.com", '测试类方法')
# rain@163.com 测试类方法
# 发送邮件

创建类和对象

面向对象编程是一种编程方式,此编程方式的落地需要使用 “类” 和 “对象” 来实现,所以,面向对象编程其实就是对 “类” 和 “对象” 的使用。

  类就是一个模板,模板里可以包含多个函数,函数里实现一些功能

  对象则是根据模板创建的实例,通过实例对象可以执行类中的函数

  • class是关键字,表示类
  • 创建对象,类名称后加括号即可
# 面向对象: 类, 对象
class Foo:
    # 创建类中的方法
    def mail(self, email, message):
        print(email, message)
        print("发送邮件")
        return True

# 调用
# 1、创建对象, 类名()
obj = Foo()
# 2、通过对象去执行方法
obj.mail("rain@163.com", '测试类方法')

# #######输出结果##########
# rain@163.com 测试类方法
# 发送邮件

并非所有场景都适合面向对象编程

总结:函数式的应用场景 --> 各个函数之间是独立且无共用的数据

面向对象三大特性

面向对象的三大特性是指:封装、继承和多态。

一、封装

封装,顾名思义就是将内容封装到某个地方,以后再去调用被封装在某处的内容。

所以,在使用面向对象的封装特性时,需要:

  • 将内容封装到某处
  • 从某处调用被封装的内容

第一步:将内容封装到某处

# 创建一个role类
class role(object):
    # 类的构造方法
    def __init__(self, name, age, job, salary):
        self.name = name
        self.age = age
        self.job = job
        self.salary = salary

    # 类的方法
    def call_role(self):
        print(self.name)
        print(self.age)
        print(self.job)
        print(self.salary)

# 将变量封装到类里name,age,job,salary里面
user1 = role('rain', 21, 'python', '2100')
user2 = role('sunny', 21, 'linux', '2000')

# self 是一个形式参数,当执行user1 = role('rain', 21, 'python', '2100')时,self 等于user1,
# 当执行user2 = role('sunny', 21, 'linux', '2000'), self 等于user1。
# 所以,内容其实被封装到了对象user1 和user2 中,每个对象中都有name,age,job,salary属性

第二步:从某处调用被封装的内容

调用被封装的内容时,有两种情况:

  • 通过对象直接调用
  • 通过self间接调用

1、通过对象直接调用被封装的内容, 对象.属性名

# 创建一个role类
class role(object):
    # 类的构造方法
    def __init__(self, name, age, job, salary):
        self.name = name
        self.age = age
        self.job = job
        self.salary = salary

# 将变量封装到类里name,age,job,salary里面
user1 = role('rain', 21, 'python', '2100')
print(user1.name)       # 直接调用user1对象的name属性
# rain

user2 = role('sunny', 21, 'linux', '2000')
print(user2.name)       # 直接调用user2对象的name属性
# sunny

 2、通过self间接调用被封装的内容

# 创建一个role类
class role(object):
    # 类的构造方法
    def __init__(self, name, age, job, salary):
        self.name = name
        self.age = age
        self.job = job
        self.salary = salary

    # 类的方法
    def call_role(self):
        print(self.name)
        print(self.age)
        print(self.job)
        print(self.salary)

# 将变量封装到类里name,age,job,salary里面
user1 = role('rain', 21, 'python', '2100')
user2 = role('sunny', 21, 'linux', '2000')
user1.call_role()
# Python默认会将user1传给self参数,即:user1.call_role(user1),所以,此时方法内部的 self = user1,即:self.name 是 raub ;self.age 是 21... # #####print###### rain 21 python 2100

 综上所述,对于面向对象的封装来说,其实就是使用构造方法将内容封装到 对象 中,然后通过对象直接或者self间接获取被封装的内容。

小明,10岁,男,上山去砍柴
小明,10岁,男,开车去东北
小明,10岁,男,最爱大保健
老李,90岁,男,上山去砍柴
老李,90岁,男,开车去东北
老李,90岁,男,最爱大保健
老张...
练习一:在终端输出如下信息
class exercise:

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    def kanchai(self):
        print("%s, %s, %s , 上山去砍柴" % (self.name, self.age, self.gender))

    def dongbei(self):
        print("%s, %s, %s , 开车去东北" % (self.name, self.age, self.gender))


user1 = exercise('小明', "21", '')
user1.kanchai()
user1.dongbei()
# 小明, 21, 男 , 上山去砍柴
# 小明, 21, 男 , 开车去东北

user2 = exercise('rain', "21", '')
user2.kanchai()
user2.dongbei()
# rain, 21, 女 , 上山去砍柴
# rain, 21, 女 , 开车去东北
练习一答案

 二、继承

继承,面向对象中的继承和现实生活中的继承相同,即:子可以继承父的内容。

通过继承创建的新类称为“子类”或“派生类”。被继承的类称为“基类”、“父类”或“超类”。

例如:

  用户1:user1 增、删、查、改

  用户2:user2 增、删、查、改

如果我们要分别为user1和user2创建一个类,那么就需要为user1和 user2 实现他们所有的功能,如下所示:

class user1:
    def __init__(self, username, passwd, role):
        self.username = username
        self.passwd = passwd
        self.role = role

    def add(self):
        print("添加%s用户成功" % self.username)

    def remove(self):
        print("删除%s用户成功" % self.username)

    def search(self):
        print("查看%s用户成功" % self.username)

    def change(self):
        print("更改%s用户成功" % self.username)


class user2:
    def __init__(self, username, passwd, role):
        self.username = username
        self.passwd = passwd
        self.role = role

    def add(self):
        print("添加%s用户成功" % self.username)

    def remove(self):
        print("删除%s用户成功" % self.username)

    def search(self):
        print("查看%s用户成功" % self.username)

    def change(self):
        print("更改%s用户成功" % self.username)

用户1与用户2都有同样的代码:

  用户1:user1 增、删、查、改

  用户2:user2 增、删、查、改

通过继承可以简化代码

#!/bin/bin/env python
# -*-coding:utf-8 -*-

class user:
    def __init__(self, username, passwd, role):
        self.username = username
        self.passwd = passwd
        self.role = role

    def add(self):
        print("添加%s用户成功" % self.username)

    def remove(self):
        print("删除%s用户成功" % self.username)

    def search(self):
        print("查看%s用户成功" % self.username)

    def change(self):
        print("更改%s用户成功" % self.username)


# 在类后面括号中写入另外一个类名,表示当前类继承另外一个类
class user1():

    def admin(self):
        print("没有继承类")


# 在类后面括号中写入另外一个类名,表示当前类继承另外一个类
class user2(user):

    def common(self):
        print(self.username)
        print(self.passwd)
        print(self.role)

# 由于没有继承user类,所以不需要参数
obj1 = user1()
obj1.admin()
# 没有继承类


# 由于继承了user类,所以需要三个参数
obj = user2('rain', '123.com', 'admin')
obj.common()

# rain
# 123.com
# admin

所以,对于面向对象的继承来说,其实就是将多个类共有的方法提取到父类中,子类仅需继承父类而不必一一实现每个方法。

注:除了子类和父类的称谓,你可能看到过 派生类 和 基类 ,他们与子类和父类只是叫法不同而已。

多继承

Python的类如果继承了多个类,那么其寻找方法的方式有两种,分别是:深度优先和广度优先

当类是经典类时,多继承情况下,会按照深度优先方式查找

当类是新式类时,多继承情况下,会按照广度优先方式查找

经典类和新式类,从字面上可以看出一个老一个新,新的必然包含了跟多的功能,也是之后推荐的写法,从写法上区分的话,如果 当前类或者父类继承了object类,那么该类便是新式类,否则便是经典类。

class D:

    def bar(self):
        print 'D.bar'


class C(D):

    def bar(self):
        print 'C.bar'


class B(D):

    def bar(self):
        print 'B.bar'


class A(B, C):

    def bar(self):
        print 'A.bar'

a = A()
# 执行bar方法时
# 首先去A类中查找,如果A类中没有,则继续去B类中找,如果B类中么有,则继续去D类中找,如果D类中么有,则继续去C类中找,如果还是未找到,则报错
# 所以,查找顺序:A --> B --> D --> C
# 在上述查找bar方法的过程中,一旦找到,则寻找过程立即中断,便不会再继续找了
a.bar()
经典类多继承
class D(object):

    def bar(self):
        print 'D.bar'


class C(D):

    def bar(self):
        print 'C.bar'


class B(D):

    def bar(self):
        print 'B.bar'


class A(B, C):

    def bar(self):
        print 'A.bar'

a = A()
# 执行bar方法时
# 首先去A类中查找,如果A类中没有,则继续去B类中找,如果B类中么有,则继续去C类中找,如果C类中么有,则继续去D类中找,如果还是未找到,则报错
# 所以,查找顺序:A --> B --> C --> D
# 在上述查找bar方法的过程中,一旦找到,则寻找过程立即中断,便不会再继续找了
a.bar()
新式类多继承

经典类:首先去A类中查找,如果A类中没有,则继续去B类中找,如果B类中么有,则继续去D类中找,如果D类中么有,则继续去C类中找,如果还是未找到,则报错

新式类:首先去A类中查找,如果A类中没有,则继续去B类中找,如果B类中么有,则继续去C类中找,如果C类中么有,则继续去D类中找,如果还是未找到,则报错

注意:在上述查找过程中,一旦找到,则寻找过程立即中断,便不会再继续找了

三、多态 

 Pyhon不支持多态并且也用不到多态,多态的概念是应用于Java和C#这一类强类型语言中

class F1:
    pass


class S1(F1):

    def show(self):
        print 'S1.show'


class S2(F1):

    def show(self):
        print 'S2.show'


# 由于在Java或C#中定义函数参数时,必须指定参数的类型
# 为了让Func函数既可以执行S1对象的show方法,又可以执行S2对象的show方法,所以,定义了一个S1和S2类的父类
# 而实际传入的参数是:S1对象和S2对象

def Func(F1 obj):
    """Func函数需要接收一个F1类型或者F1子类的类型"""
    
    print obj.show()
    
s1_obj = S1()
Func(s1_obj) # 在Func函数中传入S1类的对象 s1_obj,执行 S1 的show方法,结果:S1.show

s2_obj = S2()
Func(s2_obj) # 在Func函数中传入Ss类的对象 ss_obj,执行 Ss 的show方法,结果:S2.show
class F1:
    pass


class S1(F1):

    def show(self):
        print 'S1.show'


class S2(F1):

    def show(self):
        print 'S2.show'

def Func(obj):
    print obj.show()

s1_obj = S1()
Func(s1_obj) 

s2_obj = S2()
Func(s2_obj) 
python代码

未完待续!!!

模块

ConfigParser

用于对特定的配置进行操作,当前模块的名称在 python 3.x 版本中变更为 configparser。

用于对特定的配置文件进行操作

配置文件的格式是: []包含的叫section,    section 下有option=value这样的键值

用法:

读取配置方法

1
2
3
4
5
6
-read(filename) 直接读取ini文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型

写入配置方法

1
2
-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置
# 注释1
文件为当前路径下的configs.txt
[section1] k1
= v1 k2:v2 [section2] k1 = v1
import configparser
config = configparser.ConfigParser()
config.read('configs.txt', encoding='utf-8')

# 获取所有的节点
ret = config.sections()
print(ret)
# ['section1', 'section2']

# 获取指定节点下所有的键值对
ret1 = config.items('section1')
print(ret1)
# [('k1', 'v1'), ('k2', 'v2')]

# 获取指定节点下所有的键
ret2 = config.options('section1')
print(ret2)
# ['k1', 'k2']

# 获取指定节点下指定key的值
value = config.get('section1', 'k1')
print(value, type(value))
# 123 <class 'str'>

# 获取指定节点下指定key的值,并将其转换成int
value1 = config.getint('section1', 'k1')
print(value1, type(value1))
# 123 <class 'int'>

# 获取指定节点下指定key的值,并将其转换成float
vfloat = config.getfloat('section1', 'k1')

# 获取指定节点下指定key的值,并将其转换成bool
vbool = config.getboolean('section1', 'k1')

# 检查节点是否存在
has_sec = config.has_section('section1')
print(has_sec)
# True

# 添加节点
config.add_section('sec_1')
config.write(open('configs.txt', 'w'))

# 删除节点
config.remove_section('sec_1')
config.write(open('configs.txt', 'w'))
# 检查、删除、设置指定组内的键值对

import configparser

config = configparser.ConfigParser()
config.read('xxxooo', encoding='utf-8')

# 检查
has_opt = config.has_option('section1', 'k1')
print(has_opt)

# 删除
config.remove_option('section1', 'k1')
config.write(open('xxxooo', 'w'))

# 设置
config.set('section1', 'k10', "123")
config.write(open('xxxooo', 'w'))

 xml

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 version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

python模块解析xml

from xml.etree import ElementTree as ET

# 将字符串解析成xml特殊,root代指xml文件的根节点
str_xml = open('oldxml.xml', 'r').read()
root = ET.XML(str_xml)

# 直接解析xml文件
tree = ET.parse('oldxml.xml')

# 获取xml文件的根节点
root = tree.getroot()

# root.tag 节点名  root.attrib 节点属性
print(root.tag, root.attrib)
# data {'name': 'rain'}

# 遍历XML文档的第二层
for child in root:
    # 第二层节点的标签名称和标签属性
    print(child.tag, child.attrib)
    # 遍历XML文档的第三层
    for i in child:
        # 第二层节点的标签名称和内容
        print(i.tag, i.text)


# 遍历XML中所有的year节点
for node in root.iter('year'):
    # 节点的标签名称和内容
    print(node.tag, node.text)

由于修改的节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到文件。

from xml.etree import ElementTree as ET

############ 解析方式一 ############

# 打开文件,读取XML内容
str_xml = open('xo.xml', 'r').read()

# 将字符串解析成xml特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml)

############ 操作 ############

# 顶层标签
print(root.tag)

# 循环所有的year节点
for node in root.iter('year'):
    # 将year节点中的内容自增一
    new_year = int(node.text) + 1
    node.text = str(new_year)

    # 设置属性
    node.set('name', 'alex')
    node.set('age', '18')
    # 删除属性
    del node.attrib['name']


############ 保存文件 ############
tree = ET.ElementTree(root)
tree.write("newnew.xml", encoding='utf-8')
解析字符串方式,修改,保存
from xml.etree import ElementTree as ET

############ 解析方式二 ############

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()

############ 操作 ############

# 顶层标签
print(root.tag)

# 循环所有的year节点
for node in root.iter('year'):
    # 将year节点中的内容自增一
    new_year = int(node.text) + 1
    node.text = str(new_year)

    # 设置属性
    node.set('name', 'alex')
    node.set('age', '18')
    # 删除属性
    del node.attrib['name']


############ 保存文件 ############
tree.write("newnew.xml", encoding='utf-8')
解析文件方式,修改,保存

删除节点

from xml.etree import ElementTree as ET

############ 解析字符串方式打开 ############

# 打开文件,读取XML内容
str_xml = open('xo.xml', 'r').read()

# 将字符串解析成xml特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml)

############ 操作 ############

# 顶层标签
print(root.tag)

# 遍历data下的所有country节点
for country in root.findall('country'):
    # 获取每一个country节点下rank节点的内容
    rank = int(country.find('rank').text)

    if rank > 50:
        # 删除指定country节点
        root.remove(country)

############ 保存文件 ############
tree = ET.ElementTree(root)
tree.write("newnew.xml", encoding='utf-8')
解析字符串方式打开,删除,保存
from xml.etree import ElementTree as ET

############ 解析文件方式 ############

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()

############ 操作 ############

# 顶层标签
print(root.tag)

# 遍历data下的所有country节点
for country in root.findall('country'):
    # 获取每一个country节点下rank节点的内容
    rank = int(country.find('rank').text)

    if rank > 50:
        # 删除指定country节点
        root.remove(country)

############ 保存文件 ############
tree.write("newnew.xml", encoding='utf-8')
解析文件方式打开,删除,保存

创建XML文档

from xml.etree import ElementTree as ET


# 创建根节点
root = ET.Element("famliy")


# 创建节点大儿子
son1 = ET.Element('son', {'name': '儿1'})
# 创建小儿子
son2 = ET.Element('son', {"name": '儿2'})

# 在大儿子中创建两个孙子
grandson1 = ET.Element('grandson', {'name': '儿11'})
grandson2 = ET.Element('grandson', {'name': '儿12'})
son1.append(grandson1)
son1.append(grandson2)


# 把儿子添加到根节点中
root.append(son1)
root.append(son1)

tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
创建方式(一)
from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("famliy")


# 创建大儿子
# son1 = ET.Element('son', {'name': '儿1'})
son1 = root.makeelement('son', {'name': '儿1'})
# 创建小儿子
# son2 = ET.Element('son', {"name": '儿2'})
son2 = root.makeelement('son', {"name": '儿2'})

# 在大儿子中创建两个孙子
# grandson1 = ET.Element('grandson', {'name': '儿11'})
grandson1 = son1.makeelement('grandson', {'name': '儿11'})
# grandson2 = ET.Element('grandson', {'name': '儿12'})
grandson2 = son1.makeelement('grandson', {'name': '儿12'})

son1.append(grandson1)
son1.append(grandson2)


# 把儿子添加到根节点中
root.append(son1)
root.append(son1)

tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)
创建方式(二)
from xml.etree import ElementTree as ET


# 创建根节点
root = ET.Element("famliy")


# 创建节点大儿子
son1 = ET.SubElement(root, "son", attrib={'name': '儿1'})
# 创建小儿子
son2 = ET.SubElement(root, "son", attrib={"name": "儿2"})

# 在大儿子中创建一个孙子
grandson1 = ET.SubElement(son1, "age", attrib={'name': '儿11'})
grandson1.text = '孙子'


et = ET.ElementTree(root)  #生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False)
创建方式(三)

Subprocess模块

subprocess最早是在2.4版本中引入的。
subprocess模块用来生成子进程,并可以通过管道连接它们的输入/输出/错误,以及获得它们的返回值。
它用来代替多个旧模块和函数:
os.system
os.spawn*
os.popen*
popen2.*
commands.*

运行python的时候,我们都是在创建并运行一个进程。像Linux进程那样,一个进程可以fork一个子进程,并让这个子进程exec另外一个程序。在Python中,我们通过标准库中的subprocess包来fork一个子进程,并运行一个外部的程序。subprocess包中定义有数个创建子进程的函数,这些函数分别以不同的方式创建子进程,所以我们可以根据需要来从中选取一个使用。另外subprocess还提供了一些管理标准流(standard stream)和管道(pipe)的工具,从而在进程间使用文本通信。

使用:

1)call 

执行命令,返回状态码 shell = True ,允许 shell 命令是字符串形式

1
2
3
4
5
6
7
8
9
10
>>> import subprocess
>>> ret = subprocess.call(['ls','-l'],shell=False)
total 201056
-rw-r--r--  1 root  root         22 Jan 15 11:55 1
drwxr-xr-5 root  root       4096 Jan  8 16:33 ansible
-rw-r--r--  1 root  root       6830 Jan 15 09:41 dict_shop.py
drwxr-xr-4 root  root       4096 Jan 13 16:05 Docker
drwxr-xr-2 root  root       4096 Dec 22 14:53 DockerNginx
drwxr-xr-2 root  root       4096 Jan 21 17:30 Dockerssh
-rw-r--r--  1 root  root        396 Dec 25 17:30 id_rsa.pub

2)check_call

执行命令,如果执行状态码是 0 ,则返回0,否则抛异常

1
2
3
4
5
6
7
8
>>> subprocess.check_call(["ls", "-l"])
total 201056
-rw-r--r--  1 root  root         22 Jan 15 11:55 1
drwxr-xr-5 root  root       4096 Jan  8 16:33 ansible
-rw-r--r--  1 root  root       6830 Jan 15 09:41 dict_shop.py
>>> subprocess.check_call("exit 1", shell=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

3.check_output

执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常

1
2
subprocess.check_output(["echo""Hello World!"])
subprocess.check_output("exit 1", shell=True)

4.subprocess.Popen(...)

用于执行复杂的系统命令

参数:

  • args:shell命令,可以是字符串或者序列类型(如:list,元组)

  • bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲

  • stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄

  • preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用

  • close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
    所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。

  • shell:同上

  • cwd:用于设置子进程的当前目录

  • env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。

  • universal_newlines:不同系统的换行符不同,True -> 同意使用 

  • startupinfo与createionflags只在windows下有效
    将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等

例:

1
2
3
import subprocess
res = subprocess.Popen(["mkdir","sub"])
res2 = subprocess.Popen("mkdir sub_1", shell=True)

终端输入的命令分为两种:

  • 输入即可得到输出,如:ifconfig

  • 输入进行某环境,依赖再输入,如:python

1
>>> obj = subprocess.Popen("mkdir cwd", shell=True, cwd='/home/',)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import subprocess
 
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 ')
obj.stdin.write('print 2 ')
obj.stdin.write('print 3 ')
obj.stdin.write('print 4 ')
obj.stdin.close()
 
cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close()
 
print cmd_out
print cmd_error
1
2
3
4
5
6
7
8
9
10
import subprocess
 
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
obj.stdin.write('print 1 ')
obj.stdin.write('print 2 ')
obj.stdin.write('print 3 ')
obj.stdin.write('print 4 ')
 
out_error_list = obj.communicate()
print out_error_list
1
2
3
4
5
import subprocess
 
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_error_list = obj.communicate('print "hello"')
print out_error_list
原文地址:https://www.cnblogs.com/yxy-linux/p/5600168.html