IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> Python常用组件记录 -> 正文阅读

[Python知识库]Python常用组件记录

1、python常用框架

在这里插入图片描述1. Flask :一个用python编写的Web应用框架,它整合了Werzeug(WSGI实用工具)和Jinja2(模板引擎)两个库。它是Python Web框架族里比较年轻的一个,吸收了其他框架的优点,并且把自己的主要领域定义在了微小项目上。同时,它是可扩展的,Flask让开发者自己选择用什么数据库插件存储他们的数据。Flask是一个面向简单需求和小型应用的微框架,很多功能简单但性能卓越的网站就是基于Flask框架而搭建的。

Flask的特点:内置开发服务器和调试器;与Python单元测试功能无缝衔接;使用Jinja2模板;完全兼容WSGI 1.0标准;基于Unicode编码。

2.shelve:python的标准模块shelve用来存储数据,shelve能像python字典对象一样操作数据,将对象持久化。

3.Redmine:一款开源的问题跟踪系统,它以管理项目内的任务和Bug的问题功能为中心,兼具服务于团队开发的功能,比如与wiki和版本控制系统的联动等(http://www.redmine.org)

4.Django、Tornado、Pyramind:web应用框架;其中Django是一个遵循MMVC架构模式的开源框架,是最有代表性的Python框架。Django的优势之一是只需要单独的安装包来安装。其他的一些类似的框架需要下载很多组件才能开始工作。

同时,Django还有完善的保持更新的文档,对于开源项目来说这通常是短板。它是一个健壮的框架,很好的集成了很多来自社区的插件和扩展。项目背后的社区看上去也组织的很好,这从它非常完善的文档和教程就可以看出来。

Tornado是使用Python编写的一个强大的可扩展的Web服务器。它在处理高网络流量时表现得足够强健,却在创建和编写时有着足够的轻量级,并能够被用在大量的应用和工具中。Tornado常被用作大型站点的接口服务框架,而不像Django那样着眼于建立完整的大型网站,

Tornado的特点:完备的Web框架;是一个高效的网络库,性能与Twisted、Gevent等底层Python框架相媲美;提供高效HTTPClient;提供高效的内部HTTP服务器;完备的WebSocket支持。

Pyramid是一款轻量级的开源Python Web框架,是Pylons项目的一部分。Pyramid只能运行在Python 2.x或2.4以后的版本上。在使用后端数据库时无需声明,在开发时也不会强制使用一些特定的模板系统。

5.SQLAlchemy: ORM(对象关系映射),简单的说ORM是将数据库中的表与面向对象语言中的类建立了一种对应关系。这样,我么要操作数据库,数据库中的表或者表中的一条记录就可以直接通过操作类或者类实例来完成。而SQLAlchemy是python社区最知名的ORM工具之一。

6.mock/dummy:python接口测试;

7.Twisted是一个用Python语言编写的事件驱动的网络框架,对于追求服务器程序性能的应用,Twisted框架是一个很好的选择。

Twisted是一个高性能的编程框架,在不同的操作系统平台上,Twisted利用不同的底层技术实现了高效能通信。在开发方法上,Twisted引导程序员使用异步编程模型。Twisted提供了丰富的Defer、Threading等特性来支持异步编程。

8.Cubes:轻量级Python OLAP框架

Cubes是一个轻量级Python框架,包含OLAP、多维数据分析和浏览聚合数据(aggregated data)等工具

Cubes的主要特性之一是它的逻辑模型,抽象物理数据并提供给终端用户层。

9.Kartograph.py:创造矢量地图的轻量级Python框架

Kartograph是一个Python库,用来为ESRI生成SVG地图。Kartograph.py目前仍处于beta阶段,你可以在virtualenv环境下来测试。

10.Pulsar:Python的事件驱动并发框架

Pulsar是一个事件驱动的并发框架,有了pulsar,你可以写出在不同进程或线程中运行一个或多个活动的异步服务器。

参考:https://blog.csdn.net/qq_30068487/article/details/85837821

2、Python常用标准库

在这里插入图片描述

2.1)操作系统接口

os模块提供了很多与操作系统相关联的函数,是多方面的操作系统接口;
io:流核心工具;
time:时间的查询与转化;
argparser:命令行选项、参数和子命令的解析器
optparser:命令行选项解析器
getopt:C风格的命令行选项解析器
logging:Python日志工具
logging.config:日志配置
logging.handlers:日志处理器
getpass:简易密码输入
curses:字符显示的终端处理
curses.textpad:curses程序的文本输入域
curses.ascii:ASCII字符集工具
curses.panel:curses的控件栈扩展
platform:访问底层平台认证数据
errno:标准错误记号
ctypes:Python外部函数库
在这里插入图片描述
在这里插入图片描述

示例1:

>>> import os
>>> os.getcwd()      # 返回当前的工作目录
'C:\\Windows\system32'
>>> os.chdir('D:')   # 修改当前的工作目录到D盘根分区下
>>> os.system('mkdir python3')   # 执行系统命令 mkdir 
0                    #命令执行成功后的状态码
>>> os.listdir      #列出当前目录下的文件
<built-in function listdir>
>>> os.listdir()
['$360Section', '$Recycle.Bin', '$WINDOWS.~TMP', '360base.dll', '360Rec', '360Safe', '360安全浏览器下载', 'AeroGlass', 'Boot', 'bootmgr', 'BOOTNXT', 'BOOTSECT.BAK', 'charles', 'diskmaster000688CA', 'Documents and Settings', 'Download', 'DRIVERS', 'hiberfil.sys', 'Intel', 'IUQD', 'kingsoft', 'LanQos', 'MirantisOpenStack-9.0.iso', 'MSOCache', 'PerfLogs', 'Program Files', 'Program Files (x86)', 'ProgramData', 'python3', 'Recovery', 'swapfile.sys', 'System Volume Information', 'tcping.exe', 'uqdhd', 'uqdhd.mbr', 'Users', 'Windows', '一建', '搜狗高速下载']

注意:使用 “import os” 风格而非 “from os import *”,可以保证过程中随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()。另在使用 os 这样的大型模块时内置的 dir() 和 help() 函数非常有用。

示例2:

>>> import os
>>> dir(os)  ##会返回一个os下所有方法的列表,python3显示如下
['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']
>>> help(os.listdir)  ##返回各模块的相关帮助手册页
Help on built-in function listdir in module nt:

listdir(path=None)
    Return a list containing the names of the files in the directory.

    path can be specified as either str or bytes.  If path is bytes,
      the filenames returned will also be bytes; in all other circumstances
      the filenames returned will be str.
    If path is None, uses the path='.'.
    On some platforms, path may also be specified as an open file descriptor;\
      the file descriptor must refer to a directory.
      If this functionality is unavailable, using it raises NotImplementedError.

    The list is in arbitrary order.  It does not include the special
    entries '.' and '..' even if they are present in the directory.

针对日常的文件和目录管理任务,:mod:shutil 模块提供了一个易于使用的高级接口:

>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
>>> shutil.move('/build/executables', 'installdir')

在这里插入图片描述
其他OS常用命令:

序号方法功能
1os.access(path, mode)检验权限模式
2os.chdir(path)改变当前工作目录
3os.chflags(path, flags)设置路径的标记为数字标记。
4os.chmod(path, mode)更改权限
5os.chown(path, uid, gid)更改文件所有者
6os.chroot(path)改变当前进程的根目录
7os.close(fd)关闭文件描述符 fd
8os.closerange(fd_low, fd_high)关闭所有文件描述符,
从 fd_low (包含) 到 fd_high (不包含), 错误会忽略
9os.dup(fd)复制文件描述符 fd
10os.dup2(fd, fd2)将一个文件描述符 fd 复制到另一个 fd2

2.2、文件通配符

glob模块提供了一个函数用于从目录通配符搜索中生成文件列表

>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']

在这里插入图片描述
其他关于目录的函数还有:

os.path:通用路径名控制
fileinput:从多输入流中遍历行
stat:解释stat()的结果
filecmp:文件与目录的比较函数
tempfile:生成临时文件与目录
glob:Unix风格路径名格式的扩展
fnmatch:Unix风格路径名格式的比对
linecache:文本行的随机存储
shutil:高级文件操作
macpath:MacOS 9路径控制函数

2.3、命令行参数

通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。

sys.argv:可以用sys.argv获取当前正在执行的命令行参数的参数列表(list)。参数说明:

sys.argv[0]:当前程序名
sys.argv[1]:第一个参数
sys.argv[2]:第二个参数
len(sys.argv)-1:参数个数(减去文件名)

当在命令行中执行 “python demo.py one two three” 后可以得到以下输出结果:

>>> import sys
>>> print(sys.argv)
['demo.py', 'one', 'two', 'three']

sys 还有 stdin,stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以用于显示警告和错误信息。大多脚本的定向终止都使用 “sys.exit()”。

>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one

2.4、字符串正则匹配

re模块为高级字符串处理提供了正则表达式工具。可以说是爬虫必备,对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案:如果只需要简单的功能,应该首先考虑字符串方法,因为它们非常简单,易于阅读和调试:

>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'

如果只需要简单的功能,应该首先考虑字符串方法,因为它们非常简单,易于阅读和调试:

>>> 'tea for too'.replace('too', 'two')
'tea for two'

re.match函数:re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none,匹配成功re.match方法返回一个匹配的对象。

函数语法:re.match(pattern, string, flags=0),其中:
pattern 表匹配的正则表达式
string 表要匹配的字符串。
flags: 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。

2.5、数学计算

math模块:为浮点运算提供了对底层C函数库的访问;

>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0

但在实际工作中,math标准库往往无法满足需求,我还需要扩展库:NumPy;NumPy(Numerical Python) 支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。

另random提供了生成随机数的工具:

>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # random float
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4

2.6、互联网通信

有几个模块用于访问互联网以及处理网络通信协议。其中最简单的两个是用于处理从 urls 接收的数据的 urllib.request 以及用于发送电子邮件的 smtplib。

>>> from urllib.request import urlopen
>>> for line in urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
...     line = line.decode('utf-8')  # Decoding the binary data to text.
...     if 'EST' in line or 'EDT' in line:  # look for Eastern Time
...         print(line)

<BR>Nov. 25, 09:43:32 PM EST

>>> import smtplib
>>> server = smtplib.SMTP('localhost') ##需要本地有一个在运行的邮件服务器。
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
... """To: jcaesar@example.org
... From: soothsayer@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()

示例2:

#处理get请求,不传data,则为get请求

import urllib
from urllib.request import urlopen
from urllib.parse import urlencode

url='http://www.xxx.com/login'
data={"username":"admin","password":123456}
req_data=urlencode(data)#将字典类型的请求数据转变为url编码
res=urlopen(url+'?'+req_data)#通过urlopen方法访问拼接好的url
res=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为str

print(res)
#处理post请求,如果传了data,则为post请求

import urllib
from urllib.request import Request
from urllib.parse import urlencode

url='http://www.xxx.com/login'
data={"username":"admin","password":123456}
data=urlencode(data)#将字典类型的请求数据转变为url编码
data=data.encode('ascii')#将url编码类型的请求数据转变为bytes类型
req_data=Request(url,data)#将url和请求数据处理为一个Request对象,供urlopen调用
with urlopen(req_data) as res:
    res=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为str

print(res)

函数用法:smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

参数说明:
host: SMTP 服务器主机。 你可以指定主机的ip地址或者域名如: runoob.com,这个是可选参数。
port: 如果你提供了 host 参数, 你需要指定 SMTP 服务使用的端口号,一般情况下 SMTP 端口号为25。
local_hostname: 如果 SMTP 在你的本机上,你只需要指定服务器地址为 localhost 即可。

Python SMTP 对象使用 sendmail 方法发送邮件,语法如下:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])

参数说明:
from_addr: 邮件发送者地址。
to_addrs: 字符串列表,邮件发送地址。
msg: 发送消息


#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import smtplib
from email.mime.text import MIMEText
from email.header import Header
 
sender = 'from@runoob.com'  ##指定本地有一个在运行的邮件服务器。
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
 
# 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("菜鸟教程", 'utf-8')   # 发送者
message['To'] =  Header("测试", 'utf-8')        # 接收者
 
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
 
 
try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print "邮件发送成功"
except smtplib.SMTPException:
    print "Error: 无法发送邮件"

2.7、日期和时间

datetime模块为日期和时间处理同时提供了简单和复杂的方法。支持日期和时间算法的同时,实现的重点放在更有效的处理和格式化输出,该模块还支持时区处理。

>>> # dates are easily constructed and formatted
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368

时间的三种存在方式:时间对象,时间字符串,时间戳。以下分别示例说明:
(1)字符串转datetime:


>>> string = '2014-01-08 11:59:58'
>>> time1 = datetime.datetime.strptime(string,'%Y-%m-%d %H:%M:%S')
>>> print time1
2014-01-08 11:59:58

(2)datetime转字符串:

>>> time1_str = datetime.datetime.strftime(time1,'%Y-%m-%d %H:%M:%S')
>>> time1_str
'2014-01-08 11:59:58'

(3)时间戳转时间对象:

>>>time1 = time.localtime()
>>>time1_str = datetime.datetime.fromtimestamp(time1)

常用时间处理方法:

今天: today = datetime.date.today()
昨天: yesterday = today - datetime.timedelta(days=1)
上个月: last_month = today.month - 1 if today.month - 1 else 12
当前时间戳: time_stamp = time.time()
时间戳转:datetime datetime.datetime.fromtimestamp(time_stamp)
datetime转时间戳: int(time.mktime(today.timetuple()))
datetime转字符串: today_str = today.strftime("%Y-%m-%d")
字符串转datetime: today = datetime.datetime.strptime(today_str, “%Y-%m-%d”)
补时差: today + datetime.timedelta(hours=8)

2.8、数据压缩

以下模块可直接支持通用的数据打包和压缩格式:zlib,gzip,bz2,zipfile,以及 tarfile。

>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979

2.9、性能度量

有些用户对了解解决同一问题的不同方法之间的性能差异很感兴趣。Python 提供了一个度量工具,为这些问题提供了直接答案。

例如,使用元组封装拆封来交换元素看起来要比使用传统的方法要诱人的多,timeit 证明了现代的方法更快一些。

>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791

相对于 timeit 的细粒度,timeit:mod:profile 和 pstats 模块提供了针对更大代码块的时间度量工具。

2.10、测试模块

开发高质量软件的方法之一是为每一个函数开发测试代码,并且在开发过程中经常进行测试。doctest模块提供了一个工具,扫描模块并根据程序中内嵌的文档字符串执行测试。测试构造如同简单的将它的输出结果剪切并粘贴到文档字符串中。

通过用户提供的例子,它强化了文档,允许 doctest 模块确认代码的结果是否与文档一致:

>>> def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / len(values)

>>> import doctest
>>> doctest.testmod()   # 自动验证嵌入测试

而另一个,unittest模块不像 doctest模块那么容易使用,不过它可以在一个独立的文件里提供一个更全面的测试集:

>>> import unittest

>>> class TestStatisticalFunctions(unittest.TestCase):

    def test_average(self):
        self.assertEqual(average([20, 30, 70]), 40.0)
        self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
        self.assertRaises(ZeroDivisionError, average, [])
        self.assertRaises(TypeError, average, 20, 30, 70)

>>> unittest.main() # Calling from the command line invokes all tests

更多参见Python3 教程

附录:

学习网站:https://www.runoob.com/python3/python3-stdlib.html
https://zhuanlan.zhihu.com/c_1283796426846183424
yiibai.com/pycharm/pycharm_pyramid.html

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章           查看所有文章
加:2021-07-04 21:15:28  更:2021-07-04 21:16:25 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/3 9:51:27-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码