Python(常用模块)
模块
模块 本质上就是一个.py文件
- 内置模块(解释器层面)
- 第三方模块(Python lib文件)
- 自定义模块(当前路径) 模块调用,包的概念
在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护。
为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少,很多编程语言都采用这种组织代码的方式。在Python中,一个.py文件就称之为一个模块(Module)。
使用模块有什么好处?
最大的好处是大大提高了代码的可维护性。其次,编写代码不必从零开始。当一个模块编写完毕,就可以被其他地方引用。我们在编写程序的时候,也经常引用其他模块,包括Python内置的模块和来自第三方的模块。
使用模块还可以避免函数名和变量名冲突。相同名字的函数和变量完全可以分别存在不同的模块中,因此,我们自己在编写模块时,不必考虑名字会与其他模块冲突。但是也要注意,尽量不要与内置函数名字冲突。点这里查看Python的所有内置函数。
你也许还想到,如果不同的人编写的模块名相同怎么办?为了避免模块名冲突,Python又引入了按目录来组织模块的方法,称为包(Package)。
举个例子,一个
abc.py的文件就是一个名字叫
abc的模块,一个
xyz.py的文件就是一个名字叫
xyz的模块。
现在,假设我们的
abc和
xyz这两个模块名字与其他模块冲突了,于是我们可以通过包来组织模块,避免冲突。方法是选择一个顶层包名,比如
mycompany,按照如下目录存放:
import json i=10 s='hello' t=(1,4,6) l=[3,5,7] d={'name':"yuan"} json_str1=json.dumps(i) json_str2=json.dumps(s) json_str3=json.dumps(t) json_str4=json.dumps(l) json_str5=json.dumps(d) print(json_str1) #'10' print(json_str2) #'"hello"' print(json_str3) #'[1, 4, 6]' print(json_str4) #'[3, 5, 7]' print(json_str5) #'{"name": "yuan"}'View Code python在文本中的使用:
#----------------------------序列化 import json dic={'name':'alvin','age':23,'sex':'male'} print(type(dic))#<class 'dict'> data=json.dumps(dic) print("type",type(data))#<class 'str'> print("data",data) f=open('序列化对象','w') f.write(data) #-------------------等价于json.dump(dic,f) f.close() #-----------------------------反序列化<br> import json f=open('序列化对象') new_data=json.loads(f.read())# 等价于data=json.load(f) print(type(new_data))
''' json.load() = f.read+json.loads() json.dumps(dic)的简化:json.dump(dic,f) '''
pickle
''' 支持Python的所有数据类型,但只支持在两个Python文件之间作用 '''
##----------------------------序列化 import pickle dic={'name':'alvin','age':23,'sex':'male'} print(type(dic))#<class 'dict'> j=pickle.dumps(dic) print(type(j))#<class 'bytes'> f=open('序列化对象_pickle','wb')#注意是w是写入str,wb是写入bytes,j是'bytes' f.write(j) #-------------------等价于pickle.dump(dic,f) f.close() #-------------------------反序列化 import pickle f=open('序列化对象_pickle','rb') data=pickle.loads(f.read())# 等价于data=pickle.load(f) print(data['age'])
shelve模块
shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型
configparser模块
该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
创建文件
来看一个好多软件的常见文档格式如下:
[DEFAULT] #关键字,default 如果有的话存放默认信息,与其他字段区别开,其他字段地位一样,可以根据需要设定。default中的内容,相当于在其他每一个字段当中(此例子中的另外两个字段分别有5、6个值) ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no
如果想用python生成一个这样的文档怎么做呢?
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11':'yes' } config['bitbucket.org'] = {'User':'hg'} config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'} with open('example.ini', 'w') as configfile: config.write(configfile)
查找文件
import configparser config = configparser.ConfigParser() #---------------------------查找文件内容,基于字典的形式 print(config.sections()) # [] config.read('example.ini') print(config.sections()) # ['bitbucket.org', 'topsecret.server.com'] print('bytebong.com' in config) # False print('bitbucket.org' in config) # True print(config['bitbucket.org']["user"]) # hg print(config['DEFAULT']['Compression']) #yes print(config['topsecret.server.com']['ForwardX11']) #no print(config['bitbucket.org']) #<Section: bitbucket.org> for key in config['bitbucket.org']: # 注意,有default会默认default的键 print(key) print(config.options('bitbucket.org')) # 同for循环,找到'bitbucket.org'下所有键 print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有键值对 print(config.get('bitbucket.org','compression')) # yes get方法取深层嵌套的值
增删改操作
import configparser config = configparser.ConfigParser() config.read('example.ini') config.add_section('yuan') config.remove_section('bitbucket.org') config.remove_option('topsecret.server.com',"forwardx11") config.set('topsecret.server.com','k1','11111') config.set('yuan','k2','22222') config.write(open('new2.ini', "w"))
subprocess模块
当我们需要调用系统的命令的时候,最先考虑的os模块。用os.system()和os.popen()来进行操作。但是这两个命令过于简单,不能完成一些复杂的操作,如给运行的命令提供输入或者读取命令的输出,判断该命令的运行状态,管理多个命令的并行等等。这时subprocess中的Popen命令就能有效的完成我们需要的操作。
subprocess模块允许一个进程创建一个新的子进程,通过管道连接到子进程的stdin/stdout/stderr,获取子进程的返回值等操作。The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.
This module intends to replace several other, older modules and functions, such as: os.system、os.spawn*、os.popen*、popen2.*、commands.*
这个模块只一个类:Popen。
简单命令
import subprocess # 创建一个新的进程,与主进程不同步 if in win: s=subprocess.Popen('dir',shell=True) s=subprocess.Popen('ls') s.wait() # s是Popen的一个实例对象 print('ending...')
命令带参数
linux:
import subprocess subprocess.Popen('ls -l',shell=True) #subprocess.Popen(['ls','-l'])
控制子进程
当我们想要更个性化我们的需求的时候,就要转向Popen类,该类生成的对象用来代表子进程。刚才我们使用到了一个wait方法
此外,你还可以在父进程中对子进程进行其它操作:
s.poll() # 检查子进程状态 s.kill() # 终止子进程 s.send_signal() # 向子进程发送信号 s.terminate() # 终止子进程 s.pid:子进程号
子进程的文本流控制
可以在Popen()建立子进程的时候改变标准输入、标准输出和标准错误,并可以利用subprocess.PIPE将多个子进程的输入和输出连接在一起,构成管道(pipe):
import subprocess # s1 = subprocess.Popen(["ls","-l"], stdout=subprocess.PIPE) # print(s1.stdout.read()) #s2.communicate() s1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE) s2 = subprocess.Popen(["grep","0:0"],stdin=s1.stdout, stdout=subprocess.PIPE) out = s2.communicate() print(out)
ubprocess.PIPE实际上为文本流提供一个缓存区。s1的stdout将文本输出到缓存区,随后s2的stdin从该PIPE中将文本读取走。s2的输出文本也被存放在PIPE中,直到communicate()方法从PIPE中读取出PIPE中的文本。
注意:communicate()是Popen对象的一个方法,该方法会阻塞父进程,直到子进程完成
快捷API
''' subprocess.call() 父进程等待子进程完成 返回退出信息(returncode,相当于Linux exit code) subprocess.check_call() 父进程等待子进程完成 返回0,检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含 有returncode属性,可用try…except…来检查 subprocess.check_output() 父进程等待子进程完成 返回子进程向标准输出的输出结果 检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含 有returncode属性和output属性,output属性为标准输出的输出结果,可用try…except…来检查。 '''
- python整理七——数字的一些常用模块
- [转]常用的python模块及安装方法
- [转]常用的python模块及安装方法
- Python里的OS模块常用函数说明
- Python常用模块
- [转载] Python 常用模块整理
- Python 常用模块
- [转载]Python学习笔记三(常用模块)
- python基础31[常用模块介绍]
- 常用的python模块
- Python 中的常用数据库接口模块
- Python常用模块种类的系统介绍及与操作系统相关的调用和操作
- Python常用模块种类的系统介绍及与操作系统相关的调用和操作
- python常用模块
- 常用的python模块
- 我接触到的常用python模块
- Python常用模块种类的系统介绍及与操作系统相关的调用和操作
- Python常用模块I与操作系统相关的调用和操作
- Python常用模块资料
- python的常用模块