首页 > 技术文章 > python常用模块

menkeyi 2017-04-20 17:06 原文

import 导入模块方法

#-*- coding:utf-8 -*-
"""
help
"""
import time



print(__doc__)   #如果有文件注释那么会直接用这个方法获取
print(__file__)  #文件自身路径
print(time.__package__)#当前文件所在的文件夹
#print(__cached__) #py3采用可以给你py文件设置缓存
print(__name__,time.__name__)#只有执行的文件等于main,在一个程序中执行其它文件__name__那么就非main。
if __name__ == '__main__': 这里在以后写东西的时候加上这个判断

 

 

 

 

 

 

time和datetime模块

>>> import time

>>> time.sleep(5)  #睡觉5秒
>>> import datetime
>>> print(time.time()) #从1970年1月1日开始到现在用多少秒
1492678911.17

其它方法:

 1 import time
 2 
 3 
 4 # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
 5 # print(time.altzone)  #返回与utc时间的时间差,以秒计算\
 6 # print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
 7 # print(time.localtime()) #返回本地时间 的struct time对象格式
 8 # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
 9 
10 # print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
11 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
12 
13 
14 
15 # 日期字符串 转成  时间戳
16 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
17 # print(string_2_struct)
18 # #
19 # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
20 # print(struct_2_stamp)
21 
22 
23 
24 #将时间戳转为字符串格式
25 # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
26 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式
27 
28 
29 
30 
31 
32 #时间加减
33 import datetime
34 
35 # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
36 #print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
37 # print(datetime.datetime.now() )
38 # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
39 # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
40 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
41 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
42 
43 
44 #
45 # c_time  = datetime.datetime.now()
46 # print(c_time.replace(minute=3,hour=2)) #时间替换
View Code

 

sys模块

sys.argv           命令行参数List,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit(0)
sys.version        获取Python解释程序的版本信息
sys.maxint         最大的Int值
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]
sys

补充个方法:

sys.stdout.flush() 刷新屏幕输出,打印输出后运行这个屏幕输出就没了,然后会在原来位置输出新东西

 

增加路径:

sys.path.append("路径")#增加搜索文件的路径

 

列表中第一个是空的,在2.7中空代表当前路径。py3中是当前路径地址。

'C:\\Python27\\lib\\site-packages' 这里是存放第三方包的路径

 

利用输出做进度条:

# -*- coding:utf-8 -*-
import sys,time

for i in range(31):
    sys.stdout.write('\r')
    sys.stdout.write("%s%% %s" %(int(i/30.0*100), i*'*'))
    time.sleep(0.5)


输出:
100% ******************************
制作时间进度条

 

random模块

mport random
print random.random()
print random.randint(1,2)
print random.randrange(1,10)

 

 

json&pickle

用于序列化的两个模块

json,用于字符串 和 python数据类型间进行转换
pickle,用于python特有的类型 和 python的数据类型间进行转换
Json模块提供了四个功能:dumps、dump、loads、load   #loads内部必须是字符串

定义json返回样子
json.dumps(dic, sort_keys=True, indent=4, separators=(',', ':'))

 sort_keys:是否按照字典排序(a-z)输出,True代表是,False代表否。
 indent=4:设置缩进格数,一般由于Linux的习惯,这里会设置为4。
 separators:设置分隔符,在dic = {'a': 1, 'b': 2, 'c': 3}这行代码里可以看到冒号和逗号后面都带了个空格,这也是因为Python的默认格式也是如此,如果不想后面带有空格输出,那就可以设置成separators=(',', ':'),如果想保持原样,可以写成separators=(', ', ': ')。 

运行结果:

{

   "a":1,

   "c":3,

   "b":2

}

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

持久性就是指保持对象,甚至在多次执行同一程序之间也保持对象。通过本文,您会对 Python对象的各种持久性机制(从关系数据库到 Python 的 pickle以及其它机制)有一个总体认识。另外,还会让您更深一步地了解Python 的对象序列化能力。

pickle 可以序列化python中任何格式,但json不行只能是列表和字典。pickle缺点就是只能用于python。但json都支持

 

 

os模块

用于提供系统级操作

 1 os.getcwd()                 获取当前工作目录,即当前python脚本工作的目录路径
 2 os.chdir("dirname")         改变当前脚本工作目录;相当于shell下cd
 3 os.curdir                   返回当前目录: ('.')
 4 os.pardir                   获取当前目录的父目录字符串名:('..')
 5 os.makedirs('dir1/dir2')    可生成多层递归目录
 6 os.removedirs('dirname1')   若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
 7 os.mkdir('dirname')         生成单级目录;相当于shell中mkdir dirname
 8 os.rmdir('dirname')         删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
 9 os.listdir('dirname')       列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
10 os.remove()                 删除一个文件
11 os.rename("oldname","new")  重命名文件/目录
12 os.stat('path/filename')    获取文件/目录信息
13 os.sep                      操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
14 os.linesep                  当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
15 os.pathsep                  用于分割文件路径的字符串
16 os.name                     字符串指示当前使用平台。win->'nt'; Linux->'posix'
17 os.system("bash command")   运行shell命令,直接显示
18 os.environ                  获取系统环境变量
19 os.path.abspath(path)       返回path规范化的绝对路径
20 os.path.split(path)         将path分割成目录和文件名二元组返回
21 os.path.dirname(path)       返回path的目录。其实就是os.path.split(path)的第一个元素
22 os.path.basename(path)      返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
23 os.path.exists(path)        如果path存在,返回True;如果path不存在,返回False
24 os.path.isabs(path)         如果path是绝对路径,返回True
25 os.path.isfile(path)        如果path是一个存在的文件,返回True。否则返回False
26 os.path.isdir(path)         如果path是一个存在的目录,则返回True。否则返回False
27 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
28 os.path.getatime(path)      返回path所指向的文件或者目录的最后存取时间
29 os.path.getmtime(path)      返回path所指向的文件或者目录的最后修改时间
os模块

 

hashlib

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

 1 import hashlib
 2  
 3 #一般情况就用md5加密就行
 4 # ######## md5 ########
 5 hash = hashlib.md5()
 6 # help(hash.update)
 7 hash.update(bytes('admin', encoding='utf-8'))
 8 print(hash.hexdigest())
 9 print(hash.digest())  
10  
11  
12 ######## sha1 ########
13  
14 hash = hashlib.sha1()
15 hash.update(bytes('admin', encoding='utf-8'))
16 print(hash.hexdigest())
17  
18 # ######## sha256 ########
19  
20 hash = hashlib.sha256()
21 hash.update(bytes('admin', encoding='utf-8'))
22 print(hash.hexdigest())
23  
24  
25 # ######## sha384 ########
26  
27 hash = hashlib.sha384()
28 hash.update(bytes('admin', encoding='utf-8'))
29 print(hash.hexdigest())
30  
31 # ######## sha512 ########
32  
33 hash = hashlib.sha512()
34 hash.update(bytes('admin', encoding='utf-8'))
35 print(hash.hexdigest())
hashlib

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

1 import hmac
2  #简洁版本,加密也不错
3 h = hmac.new(bytes('898oaFs09f',encoding="utf-8"))
4 h.update(bytes('admin',encoding="utf-8"))
5 print(h.hexdigest())
hmac

 

 

 

configparser

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

[section1] # 节点
k1 = v1    # 值
k2:v2       # 值
 
[section2] # 节点
k1 = v1    # 值
提示:
模块读取配置文件中的信息都是字符串,所以值可以不用加''或"".如果加的话也是读取出来的格式还是字符串k="v",读取后就是这个格式'"v"'


 1 #-*- coding:utf-8 -*-
 2 import configparser
 3 #py2.7 需要安装 pip install configparser,py3自带
 4 
 5 con=configparser.ConfigParser()
 6 con.read("config.ini",encoding='utf-8')
 7 
 8 #获取所有节点[xxxx]
 9 print(con.sections())
10 
11 
12 #获取节点下的k:v值
13 print(con.options("zhangsan"))
14 
15 
16 结果:
17 [u'zhangsan', u'lisi']
18 [u'age', u'job']
 1 获取所有节点
 2 import configparser
 3  
 4 config = configparser.ConfigParser()
 5 config.read('xxxooo', encoding='utf-8')
 6 ret = config.sections()
 7 print(ret)
 8 
 9 
10 
11 
12 
13 获取指定节点下所有的键值对
14 config = configparser.ConfigParser()
15 config.read('xxxooo', encoding='utf-8')
16 ret = config.items('section1')
17 print(ret)
18 
19 
20 
21 获取指定节点下所有的建
22 config = configparser.ConfigParser()
23 config.read('xxxooo', encoding='utf-8')
24 ret = config.options('section1')
25 print(ret)
26 
27 
28 
29 
30 
31 
32 获取指定节点下指定key的值
33 config = configparser.ConfigParser()
34 config.read('xxxooo', encoding='utf-8')
35  
36  
37 v = config.get('section1', 'k1')
38 # v = config.getint('section1', 'k1')
39 # v = config.getfloat('section1', 'k1')
40 # v = config.getboolean('section1', 'k1')
41  
42 print(v)
43 
44 
45 
46 
47 检查、删除、添加节点
48 #将内容读到内存
49 config = configparser.ConfigParser()
50 config.read('xxxooo', encoding='utf-8')
51  
52 # 检查
53 has_sec = config.has_section('section1')
54 print(has_sec)
55  
56 # 添加节点
57 config.add_section("SEC_1")
58 config.write(open('xxxooo', 'w'))
59  
60 # 删除节点
61 config.remove_section("SEC_1")
62 config.write(open('xxxooo', 'w'))
63 
64 
65 
66 
67 检查、删除、设置指定组内的键值对
68  
69 config = configparser.ConfigParser()
70 config.read('xxxooo', encoding='utf-8')
71  
72 # 检查
73 has_opt = config.has_option('section1', 'k1')
74 print(has_opt)
75  
76 # 删除
77 config.remove_option('section1', 'k1')
78 config.write(open('xxxooo', 'w'))
79  
80 # 设置
81 config.set('section1', 'k10', "123")
82 config.write(open('xxxooo', 'w'))
增删改查操作

 

 

shutil

高级的 文件、文件夹、压缩包 处理模块

 1 shutil.copyfileobj(fsrc, fdst[, length])
 2 将文件内容拷贝到另一个文件中,可以加每次cp 文件大小
 3 import shutil
 4  
 5 shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
 6 
 7 
 8 
 9 
10 
11 shutil.copyfile(src, dst)
12 拷贝文件
13 shutil.copyfile('f1.log', 'f2.log')
14 
15 
16 
17 
18 
19 shutil.copymode(src, dst) 
20 仅拷贝权限。内容、组、用户均不变。文件内容不会cp,只是权限而已
21 shutil.copymode('f1.log', 'f2.log')
22 
23 shutil.copystat(src, dst)
24 仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
25 shutil.copystat('f1.log', 'f2.log')
26 
27 
28 
29 shutil.copy(src, dst)
30 拷贝文件和权限
31 shutil.copy('f1.log', 'f2.log')
32 
33 
34 
35 shutil.copy2(src, dst)
36 拷贝文件和状态信息
37 shutil.copy2('f1.log', 'f2.log')
38 
39 
40 
41 
42 
43 
44 
45 shutil.ignore_patterns(*patterns)
46 shutil.copytree(src, dst, symlinks=False, ignore=None)
47 递归的去拷贝文件夹
48 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
49 
50 #这个需要自行测试,symlinks=True 如果有快捷方式是cp快捷还是源文件
51 shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
52 
53 
54 
55 
56 
57 
58 shutil.rmtree(path[, ignore_errors[, onerror]])
59 递归的去删除文件
60 shutil.rmtree('folder1')
61 
62 
63 shutil.move(src, dst)
64 递归的去移动文件,它类似mv命令,其实就是重命名。
65 shutil.move('folder1', 'folder3')
66 
67 
68 
69 
70 
71 
72 
73 shutil.make_archive(base_name, format,...)
74 创建压缩包并返回文件路径,例如:zip、tar
75 创建压缩包并返回文件路径,例如:zip、tar
76 base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
77 如:www                        =>保存至当前路径
78 如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
79 format:    压缩包种类,“zip”, “tar”, “bztar”,“gztar”
80 root_dir:    要压缩的文件夹路径(默认当前目录)
81 owner:    用户,默认当前用户
82 group:    组,默认当前组
83 logger:    用于记录日志,通常是logging.Logger对象
84 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
85 import shutil
86 ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
87   
88   
89 #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
90 import shutil
91 ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
操作

shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:

import zipfile
#有写功能自己看源码的方法就行
# 压缩
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()

# 解压
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall()
#z.infolist()查看压缩包内容
#z.
extract(self, member, path=None, pwd=None) 单独解压某几个文件
z.close() zipfile解压缩
import tarfile

# 压缩
tar = tarfile.open('your.tar','w')
tar.add('/Users/wupeiqi/PycharmProjects/bbs2.log', arcname='bbs2.log')
tar.add('/Users/wupeiqi/PycharmProjects/cmdb.log', arcname='cmdb.log')
tar.close()

# 解压
tar = tarfile.open('your.tar','r')
tar.extractall()  # 可设置解压地址
tar.close()

tarfile解压缩

 

 

 

subprocess

以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。

call 

执行命令,返回状态码。命令直接输出到屏幕无法保留过程

ret = subprocess.call(["ls""-l"], shell=False)#默认可以不用加shell

ret = subprocess.call("ls -l", shell=True)   #区别在于这个可以直接写命令和参数,如果==true 那么就的写成上面列表的格式
 

check_call

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

subprocess.check_call(["ls""-l"])

subprocess.check_call("exit 1", shell=True)
 
check_output
执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常
subprocess.check_output(["echo""Hello World!"])
subprocess.check_output("exit 1", shell=True)
 
 
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 -> 同意使用 \n
  • startupinfo与createionflags只在windows下有效
    将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
1 import subprocess
2 ret1 = subprocess.Popen(["mkdir","t1"])
3 ret2 = subprocess.Popen("mkdir t2", shell=True)
普通命令

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

  • 输入即可得到输出,如:ifconfig
  • 输入进行某环境,依赖再输入,如:python
1 import subprocess
2 #cwd就是到当前的目录在执行创建文件夹的命令
3 obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
View Code
 1 import subprocess
 2 #这里定义了三个管道stdin输入,stdout输出,stderr错误。
 3 #复杂的地方在于先执行python解释器,然后程序会等待命令的输入
 4 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
 5 
 6 #输入命令
 7 obj.stdin.write("print(1)\n")
 8 obj.stdin.write("print(2)")
 9 #结束输入管道
10 obj.stdin.close()
11 
12 
13 #获取输出信息
14 cmd_out = obj.stdout.read()
15 obj.stdout.close()
16 cmd_error = obj.stderr.read()
17 obj.stderr.close()
18 
19 print(cmd_out)
20 print(cmd_error)
复杂1
 1 import subprocess
 2 
 3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
 4 obj.stdin.write("print(1)\n")
 5 obj.stdin.write("print(2)")
 6 
 7 
 8 #这里主要就是用communicate  直接获取输出结果(错误和正常结果)
 9 out_error_list = obj.communicate()
10 print(out_error_list)
11 
12 
13 结果:
14 ('1\n', 'Traceback (most recent call last):\n  File "<stdin>", line 2, in <module>\nNameError: name \'asd\' is not defined\n')
复杂2
1 import subprocess
2 
3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
4 
5 #如果执行一条命令的话 可以直接用communicate 输入命令
6 out_error_list = obj.communicate('print("hello")')
7 print(out_error_list)
复杂3

 

 
 logging
用于便捷记录日志且线程安全的模块
import logging
  
  
logging.basicConfig(filename='log.log',
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=10)
  
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')

"""日志等级,日志等级大于等于上面的level 才可以被记录到日志里面
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
"""
使用方法

日志记录格式 

 1 # 定义文件
 2 file_1_1 = logging.FileHandler('l1_1.log', 'a', encoding='utf-8')
 3 #定义格式
 4 fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s")
 5 #应用格式
 6 file_1_1.setFormatter(fmt)
 7 
 8 file_1_2 = logging.FileHandler('l1_2.log', 'a', encoding='utf-8')
 9 fmt = logging.Formatter()
10 file_1_2.setFormatter(fmt)
11 
12 # 定义日志级别,记录日志信息
13 logger1 = logging.Logger('s1', level=logging.ERROR)
14 logger1.addHandler(file_1_1)
15 logger1.addHandler(file_1_2)
16 
17 
18 # 写日志
19 logger1.critical('1111')
多日志文件1

 

 

推荐阅读