分享

学Python的初体验——模块简述

 千锋Python学堂 2019-12-10

Python的模块有很多很多,就像纷乱繁杂的API,都分别归属于这些模块,假如我们明白了哪个模块干什么事,能干什么,能做到什么,或者说 —— 理论上作为大众应用如此广泛的它应该能做到什么,那即使我们不知道API,Google或百度的时候也有方向,有一个精准的搜索关键词,这对于我们解决问题的效率来讲,至关重要。

Python的模块,你可以理解成就是一个个的js文件,或者说处理不同领域事情的util工具类。比如用于操作系统相关的os,用于系统指令相关的sys,用于发送请求的requests,用于线程管理的thread和threading,用于数学计算,随机数处理,字符串匹配的math、random和re,用于时间相关操作的time、datetime和calendar,用于连接MySQL数据库的pymysql(不同数据库有不同的包),用于处理json相关的json…有很多很多,还有类似于node stream那样的管道操作流操作的包,用于消息队列的包(比如处理kafka相关的东西)等等第三方包,数不尽,用不竭,其实也正因为有这样的生态,它才能茁壮长大。(回想当初,连一个高低电平的变换都要自己来实现,想想都是泪。。。不过方便的同时,也把我们都变成了一个个的API调用者= =,好吧,扯远了、、、)

我们一个个看:

1、os模块 —— 文件操作系统:

os,经常装系统的人可能经常会说,os镜像,xxxx.os文件等等,其实os的意思是Operating System,也就是操作系统,既然是操作系统,操作文件,那应该跟node的fs差不多吧,不管怎样,来看一下。
既然是操作系统和文件,那应该会有新建,修改,文件路径,打开,关闭,读取文件等等的基本操作,也会有文件权限,文件重命名等等的操作,就像node中的fs.read、fs.close、fs.path…,而Python中的os模块,这些操作也是有的,它也是os.close,os.read,os.mkdir,os.open,os.rename等等。。。是不是发现也特别像JavaScript?

def test_os(self):
print('os_start')
print('当前绝对路径为:' + os.path.abspath('./'))
path = os.path.abspath('./')

if not os.path.exists(path + '/hello'): # 判断路径是否存在
os.mkdir(path + '/hello') # 建路径

# 类似JavaScript中的try catch,异常捕获
try:
# 建文件,这种方式是默认的建文件方式,如txt是gbk的编码格式,若需要储存成另外编码格式的,可以通过codecs模块来创建文件
# f = open(path + '/hello/test.txt', 'w')

f = codecs.open(path + '/hello/test.txt', 'w', 'utf-8') # 建文件
f.write('hello world, 你好啊, \n')
f.close()

except Exception as error:
print('创建并写入文件时报错:' + str(error))

print('当前工作目录为:' + os.getcwd())

# 文件重命名 —— rename / renames
os.rename(path + '/hello/test.txt', path + '/hello/hello.txt') # 将之前的test.txt文件重命名为hello.txt文件

print('os_end')

2、sys模块 —— 系统指令与信息:

直接贴吧,主要是读取信息

def test_sys(self):

print(sys.argv) # 获取命令行的参数,就比如我们刚刚执行了python ./package.py,这里就会在结果list里面返回,[程序名,argv0,1,2,...]

# print(sys.modules) # 当前引入的模块信息
print(sys.platform) # 操作平台信息
print(sys.version) # python版本信息
print(sys.copyright) # python的版权信息

# print(sys.getswitchinterval()) # 线程切换间隔
# print(sys.thread_info) # 当前线程信息

# print(sys.stdin) # 输入相关
# print(sys.stdout) # 输出相关
# print(sys.stderr) # 错误相关
# ...

3、requests模块 —— http通讯:

既然requests是发http请求,处理通讯,按照我们的一般对于http或者更广泛点的Tcp的理解,既然是请求,那就有get、post、put跟delete,实际上也是这样的,requests.get,requests.post,requests.put,requests.delete,当然,还有一个综合性的将get、post等等类型当做参数传进去的requests.request。而且,注意,这是后台,后台,后台!重要的事情说3遍,你不用再去管跨域,不存在跨域。。。记得有一次在闲聊的时候聊到前端接口调不通,我跟他提了跨域,然后有一次他后台调不通了,他也以为是跨域,我用nginx,他也搞了一个nginx…

def test_requests(self):

def getData():
resp = requests.get('https://www.imooc.com/article/getarticlelist?marking=fe&page=4')
return resp.content

def requestData():
resp = requests.request('GET', 'https://www.imooc.com/article/getarticlelist?marking=fe&page=4')
return resp.content

# requests.get
# requests.post
# requests.put
# requests.delete

# requests.request

# 此外它还有,不常用的,可暂不理会
# requests.head
# requests.patch

print(getData())
print(requestData())

4、thread和threading模块 —— 线程管理:

python通过thread跟threading来管理线程,先导入模块

import _thread # thread与threading有冲突,python3在原有的基础上增加了一个_私有前缀,不影响使用
import threading # threading更高级,也可以代替旧的thread,我们日常用threading就可以啦。

看看它是怎么用的:

def test_threading (self):

# 开多条线程

def run():
print('当前执行的线程为:' + str(threading.current_thread()))
time.sleep(2)

thread_list = []
i = 5
while i > 0:
t = threading.Thread(target=run)
thread_list.append(t)
i -= 1

for t in thread_list:
t.start()

5、time、datetime和calendar模块 —— 日历、时间:

看到上面的线程管理代码时,里面我们很熟悉的sleep函数就来自于time模块。获取时间,这里就没什么需要说的了,不过它本身附带的格式化是比较好用的了,无需像JavaScript那样去getFullYear()或去单独实现格式化。

def test_time(self):

print(time.time()) # 时间戳
print(time.localtime()) # 当地时间
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())) # 当地时间,格式化成带星期几格式
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) # 当地时间,并做格式化成2019-11-27 20:00:00

print(datetime.date.today()) # 年月日
print(datetime.date(2019, 11, 27)) # 年月日

print(calendar.month(2019, 11)) # 生成日历页
print(calendar.isleap(2020)) # 判断传入的年份是否为闰年
print(calendar.month(2019, 11, w=3, l=2)) # 修改日历行列间距,这里是3字符和2字符
print('\ntime和datetime')

简单看看输出:

学Python的初体验——模块简述

6、json模块 —— 处理json:

def test_json(self):

obj = {
'a': 1,
'b': 2
}
objStr = json.dumps(obj) # JavaScript里的JSON.stringify —— 序列化
print(objStr)
print(json.loads(objStr)) # JavaScript里的JSON.parse —— 解析

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多