python popen模块_python 模块

类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。

如:os 是系统相关的模块;file是文件操作相关的模块

模块分为三种:

自定义模块

第三方模块

内置模块

自定义模块

1、定义模块

情景一:

情景二:

情景三:

2、导入模块

Python之所以应用越来越广泛,在一定程度上也依赖于其为程序员提供了大量的模块以供使用,如果想要使用模块,则需要导入。导入模块有一下几种方法:

导入模块其实就是告诉Python解释器去解释那个py文件

导入一个py文件,解释器解释该py文件

导入一个包,解释器解释该包下的 __init__.py 文件 【py2.7】

那么问题来了,导入模块时是根据那个路径作为基准来进行的呢?即:sys.path

如果sys.path路径列表没有你想要的路径,可以通过 sys.path.append('路径') 添加。

模块

内置模块是Python自带的功能,在使用内置模块相应的功能时,需要【先导入】再【使用】

一、sys

用于提供对Python解释器相关的操作:

importsys

importtime

defview_bar(num, total):

rate = float(num) /float(total)

rate_num = int(rate * 100)

r = '\r%d%%' %(rate_num, )

sys.stdout.write(r)

sys.stdout.flush()

if __name__ == '__main__':

for i in range(0, 100):

time.sleep(0.1)

view_bar(i, 100)

二、os

用于提供系统级别的操作:

三、hashlib

用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法

以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。

python内置还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密

四、random

importrandom

checkcode = ''

for i in range(4):

current = random.randrange(0,4)

if current !=i:

temp = chr(random.randint(65,90))

else:

temp = random.randint(0,9)

checkcode +=str(temp)

print checkcode

五、re

python中re模块提供了正则表达式相关操作

字符:

. 匹配除换行符以外的任意字符  \w匹配字母或数字或下划线或汉字  \s匹配任意的空白符  \d匹配数字  \b匹配单词的开始或结束  ^匹配字符串的开始  $匹配字符串的结束

次数:

* 重复零次或更多次  +重复一次或更多次  ?重复零次或一次  {n}重复n次  {n,}重复n次或更多次  {n,m}重复n到m次

match

#无分组

r = re.match("h\w+", origin)

print(r.group()) #获取匹配到的所有结果

print(r.groups()) #获取模型中匹配到的分组结果

print(r.groupdict()) #获取模型中匹配到的分组结果

#有分组

#为何要有分组?提取匹配成功的指定内容(先匹配成功全部正则,再匹配成功的局部内容提取出来)

r = re.match("h(\w+).*(?P\d)$", origin)

print(r.group()) #获取匹配到的所有结果

print(r.groups()) #获取模型中匹配到的分组结果

print(r.groupdict()) #获取模型中匹配到的分组中所有执行了key的组

search

#无分组

r = re.search("a\w+", origin)

print(r.group()) #获取匹配到的所有结果

print(r.groups()) #获取模型中匹配到的分组结果

print(r.groupdict()) #获取模型中匹配到的分组结果

#有分组

r = re.search("a(\w+).*(?P\d)$", origin)

print(r.group()) #获取匹配到的所有结果

print(r.groups()) #获取模型中匹配到的分组结果

print(r.groupdict()) #获取模型中匹配到的分组中所有执行了key的组

findall

#无分组

r = re.findall("a\w+",origin)

print(r)

#有分组

origin = "hello alex bcd abcd lge acd 19"r = re.findall("a((\w*)c)(d)", origin)

print(r)

sub

#与分组无关

origin = "hello alex bcd alex lge alex acd 19"r = re.sub("a\w+", "999", origin, 2)

print(r)

split

#无分组

origin = "hello alex bcd alex lge alex acd 19"r = re.split("alex", origin, 1)

print(r)

#有分组

origin = "hello alex bcd alex lge alex acd 19"r1 = re.split("(alex)", origin, 1)

print(r1)

r2 = re.split("(al(ex))", origin, 1)

print(r2)

IP:

^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$

手机号:

^1[3|4|5|8][0-9]\d{8}$

邮箱:

[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+

六、序列化

Python中用于序列化的两个模块

json     用于【字符串】和 【python基本数据类型】 间进行转换

pickle   用于【python特有的类型】 和 【python基本数据类型】间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

七、configparser

configparser用于处理特定格式的文件,其本质上是利用open来操作文件。

# 注释1

;注释2

[section1]# 节点

k1 =v1 # 值

k2:v2 # 值

[section2]# 节点

k1 = v1 # 值

1、获取所有节点

2、获取指定节点下所有的键值对

3、获取指定节点下所有的建

4、获取指定节点下指定key的值

5、检查、删除、添加节点

6、检查、删除、设置指定组内的键值对

八、XML

XML是实现不同语言或程序之间进行数据交换的协议,XML文件格式如下:

2

2023

141100

5

2026

59900

69

2026

13600

1、解析XML

from xml.etree importElementTree as ET

#打开文件,读取XML内容

str_xml = open('xo.xml', 'r').read()

#将字符串解析成xml特殊对象,root代指xml文件的根节点

root = ET.XML(str_xml)

from xml.etree importElementTree as ET

#直接解析xml文件

tree = ET.parse("xo.xml")

#获取xml文件的根节点

root = tree.getroot()

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:

text...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 "" % (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 SubElem

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值