常用内置模块介绍(自动化运维-8)

一、os 模块

用于提供系统级别的操作

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

二、sys 模块

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

 

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

 三、hashlib

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

加密操作

 

import hashlib
#md5 加密操作,使用那个算法,就引用那个函数
hash = hashlib.md5()
hash.update("zhong guo".encode(encoding="utf-8"))
#十六进制显示结果
print(hash.hexdigest())

 

 添加自定义的key进行加密

import hashlib
#md5 加密操作,使用那个算法,就引用那个函数
# 传入自定义的key bushaoxun,在 pthon3中必须是bytes类型
hash = hashlib.md5(b"bushaoxun")
hash.update("zhong guo".encode(encoding="utf-8"))
print(hash.hexdigest())

四、json 和 pickle

用于序列化的两个模块

  • json,用于字符串 和 python数据类型间进行转换
  • pickle,用于python特有的类型 和 python的数据类型间进行转换

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

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

pickle 模块和 json 模块使用方法一致,不同的是 pickle 只是 python 内部进行数据类型转换的工具

import json
person = {"姓名":"bushaoxun","年龄":28}
#json dump有一个ensure_ascii参数,当它为True的时候,所有非ASCII码字符显示为\uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。
#将python类型的数据转换为其他语言识别的字符串
a = json.dumps(person,ensure_ascii=False)
print(a)
#将其他语言识别的字符串转换为 python 类型的数据
b = json.loads(a)
print(b)

#转换成其他语言认识的字符串并写入文件,然后从文件转换为python类型。
import json
person = {"姓名":"bushaoxun","年龄":28}
with open('wpic.txt','w',encoding="utf-8") as f:
    json.dump(person,f,ensure_ascii=False,)
with open('wpic.txt','r',encoding="utf-8") as g:
    c = json.load(g)
print(c)

五、shutil 模块

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

下面列举和测试几个常用的功能

拷贝文件:

import shutil
# 复制文件,如果目标文件存在就覆盖
shutil.copyfile("D:\\新建文本文档.txt","D:\\中国.txt")

 拷贝文件和权限

import shutil
shutil.copy("D:\\新建文本文档.txt","D:\\中国.txt")

 创建压缩包并返回文件路径,例如:zip、tar

 shutil.make_archive(base_name, format,...)

    base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
        如:www   =>保存至当前路径
        如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/

    format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”

    root_dir: 要压缩的文件夹路径(默认当前目录)

    owner: 用户,默认当前用户

    group: 组,默认当前组

    logger: 用于记录日志,通常是logging.Logger对象

import shutil
shutil.make_archive("D:\\test","zip","D:\\2345Downloads")

 六、shelve 模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式

使用 shelve  存取数据到文件

import shelve
d = shelve.open('shelve_test')  # 打开一个文件,
class Test(object):
    def __init__(self, name):
        self.name = name
t1 = Test("wpic")
t2 = Test("wpicbushaoxun")
person = ["bushaoxun", "mail", "hebei"]
d["test"] = person  # 持久化列表
d["t1"] = t  # 持久化类
d["t2"] = t2
d.close

使用 shelve 从文件读取数据,另一种写法

import shelve
with shelve.open('student') as db:
    db['name'] = 'bushaoxun'
    db['age'] = 30
    db['hobby'] = ['篮球', '看电影', '弹吉他']
with shelve.open('student') as db:
    for key,value in db.items():
        print(key, ': ', value)

七、configparser 模块

用于生成和修改常见配置文档

示例文件,mysql 配置文件

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
symbolic-links=0

[mysqld_safe]
log-error=/var/log/mariadb/mariadb.log
pid-file=/var/run/mariadb/mariadb.pid
includedir /etc/my.cnf.d

创建配置文件

import configparser
config = configparser.ConfigParser()

config["mysqld"] = {"datadir":"/var/lib/mysql",
                      "socket":"/var/lib/mysql/mysql.sock",
                      "symbolic-links":"0"}
config["mysqld_safe"] = {"log-error":"/var/log/mariadb/mariadb.log",
                           "pid-file":"/var/run/mariadb/mariadb.pid"}

with open('my.cnf', 'w') as mysql:
   config.write(mysql)

读取配置文件

import configparser
config = configparser.ConfigParser()
print(config.sections()) # 打印标题,此时为空,因为并没有读取配置文件
print(config.read("my.cnf")) # 读取文件
print(config.sections()) # 此时可以打印出标题
# 以下是依据标题取出数据
print(config[config.sections()[0]]["datadir"])
print(config["mysqld_safe"]["pid-file"])
for k,v in config["mysqld"].items():
    print(k,"=",v)

 configparser增删该查语法

import configparser
config = configparser.ConfigParser()
#+++++++++读取数据+++++++++
config.read("my.cnf")
#获取标题
content = config.sections()
print(content)
#获取标题下的key
options = config.options("mysqld")
print(options)
#获取key 和 value,返回列表
item_list = config.items("mysqld")
#根据 key 获取 value,第一个参数为标题,第二个参数为标题下的key
value = config.get("mysqld","socket")
print(value)
#++++++++更改数据++++++++
#删除标题及其标题下的内容
config.remove_section("mysqld")
#config.write(open("my.cnf","w"))
#添加标题
config.has_section('test') # 测试有没有标题test,返回布尔值
config.add_section("test") # 添加标题test,
config.set("test","age","22") # 标题下添加 key 和 value,如果key存在,则不添加. 而是更改value的值
config.remove_option("test","age") # 移除标题下的 key,如果没有不会报错
config.write(open("my.cnf","w")) # 写入文件,以追加的方式

 八、logging 模块

python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug()info()warning()error() and critical() 5个级别

简单用法

import logging
logging.warning('Memory is not enough')
logging.critical('web is down,please check your server')

#输出
WARNING:root:Memory is not enough
CRITICAL:root:web is down,please check your server

 把日志写到文件中

import logging
# 把日志写到文件中
# logging.basicConfig(filename='web.log',level=logging.INFO)
#把日志写到文件中,并记录时间
logging.basicConfig(filename='web.log',level=logging.DEBUG,format='%(asctime)s %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
logging.info('log will write to web.log file')
logging.warning('Memory is not enough')
logging.critical('web is down,please check your server')

 九、random 模块

生成随机数

import random
print(random.random())
print(random.randint(1,5)) #返回1-5之间的随机数,整数类型。
print(random.randrange(0,10,2))#返回0-9之间的随机数,整数类型,可以设置步长

 生产随机验证码

import random
authcode = ''
for i in range(4):
    v = random.randrange(0,4)
    if v != i: #经测试使用不等于生成字母较多,使用等于生成数字较多
        value = chr(random.randint(65,90))#生成 A-Z 随机字母,chr()转换数字为字母,ord()转换字母为数字
    else:
        value = random.randint(0,9)
    authcode += str(value)
print(authcode)

 十、time 和 time datetime 模块

time模块

import time
print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
print(time.altzone)  #返回与utc时间的时间差,以秒计算\
print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
print(time.localtime()) #返回本地时间 的struct time对象格式
print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式

print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上

# 日期字符串 转成  时间戳
string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
print(string_2_struct)
struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
print(struct_2_stamp)

#将时间戳转为字符串格式
print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式

 datetime

import datetime
print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
print(datetime.datetime.now() )
print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30

c_time  = datetime.datetime.now()
print(c_time.replace(minute=3,hour=2)) #时间替换

 

posted @ 2018-03-14 17:03  步绍训  阅读(211)  评论(0)    收藏  举报