python 常用模块
常用模块
- time
- datetime
- logging
- platform
- os
- sys
- subprocess
- re
- shutil
- json
- pickle
- random
- hashlib
- configparser
- rediscluster
time 模块
import time # 时间戳 print(time.time()) 1492504530.6282418 # 线程指定推迟时间运行(单位是秒) time.sleep(5) # 年月日 print(time.strftime("%Y%m%d", time.localtime())) 20170418 # 相当于linux下的date print(time.asctime()) Tue Apr 18 16:35:30 2017 print(time.ctime()) Tue Apr 18 16:35:30 2017 # 返回本地时间 的struct time对象格式 print(time.localtime()) time.struct_time(tm_year=2017, tm_mon=4, tm_mday=18, tm_hour=16, tm_min=31, tm_sec=34, tm_wday=1, tm_yday=108, tm_isdst=0) # 用法,可以单独的把数据读出来支持列表方式和命名方式 stime = time.localtime() print(stime.tm_year, stime.tm_mday, stime[5]) 2017 18 30
datetime 模块
import datetime print(datetime.datetime.now()) 2017-04-18 16:35:30.629241 #当前时间+3天 print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间-3天 print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间+3小时 print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+30分 print(datetime.datetime.now() + datetime.timedelta(minutes=30))
logging 模块
之前有需求记录日志都是自己写用拼凑的方式再写入到文件里,那样没有效率很低,而且格式也是固定;使用logging模块可以快速解决这种需求
logging一共有5个级别: debug, info, warning, error, critical
输出到屏幕
import logging
logging.debug("user [cuix] hh,you has been debug!")
logging.info("user [cuix] he,you has been info!")
logging.warning("user [cuix] hello,you has been warning!")
logging.error("user [cuix] hi,you has been error!")
logging.critical("user [cuix] ha,you has been critical!!!")
#输出,默认显示warning级别以上的,而debug,info不显示
WARNING:root:user [cuix] hello,you has been warning!
ERROR:root:user [cuix] hi,you has been error!
CRITICAL:root:user [cuix] ha,you has been critical!!!
写入到文件
import logging
# 把需要的级别日志往文件中写入,设置级别为warning以下的写入文件中
# logging.basicConfig(filename='test.log', level=logging.WARNING)
# 加上时间
logging.basicConfig(filename='test.log',
format='%(asctime)s %(message)s %(filename)s-%(lineno)d',
datefmt='%m/%d/%Y %I:%M:%S %p')
logging.debug("user [cuix] hh,you has been debug!")
logging.info("user [cuix] he,you has been info!")
logging.warning("user [cuix] hello,you has been warning!")
logging.error("user [cuix] hi,you has been error!")
logging.critical("user [cuix] ha,you has been critical!!!")
设置日志格式 format
%(name)s Logger的名字 %(levelno)s 数字形式的日志级别 %(levelname)s 文本形式的日志级别 %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有 %(filename)s 调用日志输出函数的模块的文件名 %(module)s 调用日志输出函数的模块名 %(funcName)s 调用日志输出函数的函数名 %(lineno)d 调用日志输出函数的语句所在的代码行 %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示 %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数 %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 %(thread)d 线程ID %(threadName)s 线程名 %(process)d 进程ID %(message)s 用户输出的消息
来个屌的,日志截断
import time
from logging import handlers
logger = logging.getLogger(__name__)
log_file = 'time.log'
# 以大小为单位截断日志(日志文件的末尾为跟数字)
#fh = handlers.RotatingFileHandler(filename=log_file, maxBytes=8, backupCount=3)
# 以时间为单位截断日志 S(秒) D(天) H(小时) M(分) W(星期) midnight(凌晨) interval是时间间隔, backupCount是备份的次数
# 日志末尾会跟时间,以-为分割
fh = handlers.TimedRotatingFileHandler(filename=log_file, when="S", interval=3, backupCount=3)
formatter = logging.Formatter('%(asctime)s %(module)s %(lineno)s %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.warning("user [cuix] hello,you has been warning!")
logger.warning("user [123] hello,you has been warning!")
time.sleep(3)
logger.warning("user [32323] hello,you has been warning!")
logger.error("user [cuix] hi,you has been error!")
time.sleep(3)
logger.critical("user [cuix] ha,you has been critical!!!")
logger.warning("user [32323] hello,you has been warning!")
logger.warning("user [32323] hello,you has been warning!")
platform 模块
>>> import platform
# 系统内核及版本
>>> platform.platform()
'Linux-3.10.0-327.28.3.el7.x86_64-x86_64-with-centos-7.2.1511-Core'
# 系统的类型
>>> platform.system()
'Linux'
#系统的hostname
>>> platform.node()
'localhost.localdomain'
# 系统内核信息
>>> platform.release()
'3.10.0-327.28.3.el7.x86_64'
# 系统的架构
>>> platform.machine()
'x86_64'
# 系统信息
>>> platform.uname()
('Linux', 'localhost.localdomain', '3.10.0-327.28.3.el7.x86_64', '#1 SMP Thu Aug 18 19:05:49 UTC 2016', 'x86_64', 'x86_64')
# python 版本
>>> platform.python_version()
'3.5.2'
# 执行系统的命令
>>> platform.popen('ls').read()
# 系统类型及版本号
>>> platform.linux_distribution()
('CentOS Linux', '7.2.1511', 'Core')
os 模块
import os
# 查看系统路径
os.path
# 执行系统命令
os.system('ls')
# 获取当前工作目录,即当前python脚本工作的目录路径
os.getcwd()
# 删除一个文件,需要指定文件名
os.remove('test.txt')
# 创建一个目录
os.mkdir('dirname')
# 删除一个目录
os.rmdir('dirname')
# 修改文件名或目录
os.rename('oldname','newname')
# 切换路径
os.chdir('path')
# 列出所有文件,以列表形式显示
os.listdir('dirname')
# 返回path规范化的绝对路径
os.path.abspath('path')
# 将path分割成目录和文件名二元组返回
os.path.split('path')
# 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.dirname('path')
# 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.basename('path')
# 如果path存在,返回True;如果path不存在,返回False
os.path.exists('path')
# 如果path是绝对路径,返回True
os.path.isabs('path')
# 如果path是一个存在的文件,返回True。否则返回False
os.path.isfile('path')
# 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.isdir('path')
# 返回path所指向的文件或者目录的最后存取时间
os.path.getatime('path')
# 返回path所指向的文件或者目录的最后修改时间
os.path.getmtime('path')
路径拼接(经常用)
import os # 获取项目的根路径 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 拼接路径(下面是切换到项目根目录下的db/admin的路径下) os.path.join(BASE_DIR,'db','admin')
程序中还经常对一些文件或者目录判断是否存在进行操作
import os os.path.isfile('test.txt') #如果不存在就返回False os.path.exists(directory) #如果目录不存在就返回False # 如下判断,目录是否存在,若不存在则创建 if os.path.exist('/dirctory') is False: os.mkdir('dirctory', 0755)
获取文件的状态等各种信息
import os
>>> os.stat('socket_server.py')
posix.stat_result(st_mode=33188, st_ino=404720296, st_dev=64771L, st_nlink=1, st_uid=0, st_gid=0, st_size=961, st_atime=1493623080, st_mtime=1493623079, st_ctime=1493623079)
# 文件的大小
>>> os.stat('socket_server.py').st_size
961
sys 模块
# 命令行参数List,第一个元素是程序本身路径
sys.argv
sys.argv[1] # 表示传入的第一个参数
# 退出程序,正常退出时exit(0)
sys.exit(n)
# 获取Python解释程序的版本信息
sys.version
# 最大的Int值
sys.maxint
# 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.path
# 返回操作系统平台名称
sys.platform
# 增加环境路径
sys.path.append('path')
# 经常会这样用,实现不同目录间的程序调用
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
re 正则
subprocess 模块
# 调用系统命令
import subprocess
# getstatusoutput 会有返回执行结果的返回值和执行结果
# 如果返回值为 0 表示执行成功
status = subprocess.getstatusoutput('ls')
if status[0] != 0:
print('命令执行有异常!')
# getoutput 返回执行命令的结果,不管是否执行成功都会把结果返回
out_put = subprocess.getoutput(('ls')
print(out_put)
# 还有其它用法,不过我觉得上面这两个就已经能满足需求了,而且用起来比下面的方便
# check_call
# call
import subprocess result = subprocess.Popen("cmd", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) result.stdin.write("yes\rnn") result.stdin.flush()
shutil 模块 (文件复制)
import shutil # copy文件复制 shutil.copy('源文件名', '复制后的文件名') # copyfile 也是用于文件的复制 shutil.copyfile('源文件名', '复制后的文件名') # chown 给目录或者文件增加权限 shutil.chown('path', 'user', 'group') # copystat 复制文件的mtime,ctime,atime值到一个文件上 shutil.copystat('源文件', '需要存在的目标文件') # move 把源文件移动到指定的文件 shutil.move('源文件', '目标文件') # copytree copymode 这两种用法很少用,可以自行补脑
json 模块
import json
dic = {'a': 1, 'b': 2, 'c': 3}
# 把字典写入文件中
with open('json.txt', 'w') as f:
f.write(json.dumps(dic))
# 从文件中读出写入的字典数据
with open('json.txt') as f:
new_dic = json.load(f)
print(new_dic)
# 执行结果:
{'a': 1, 'b': 2, 'c': 3}
pickle 模块
import pickle
dic = {
'a': 11,
'b': 33,
'c': 222
}
# 把数据写入到文件,python3需要使用wb
pickle.dump(dic, open('test.log', 'wb'))
# 从文件中把数据读出来,python3需要使用rb
obj = pickle.load(open('test.log', 'rb'))
print(obj)
random 模块
import random # randrange 随机数是1-9而不会是10 >> print(random.randrange(1, 10)) # randint 随机数是1-10 包括10 >> print(random.randint(1, 10)) # 是一个内在地址 >> print(random.random)
# 随机从一个列表中获取元素
>> random.choice(list)
hashlib 模块
# 生成根据时间的md5 import hashlib import time # 对字符串进行加密 hash = hashlib.md5() hash.update(b'abc') print(hash.hexdigest()) # 生成根据时间的md5 hash = hashlib.md5() hash.update(bytes(str(time.time()), encoding='utf-8')) print(hash.hexdigest())
md5 sha1 sha256 sha384 sha512 加密
# md5 加密
m = hashlib.md5()
print(m.hexdigest())
# sha1 加密
m = hashlib.sha1()
m.update('admin'.encode('utf-8'))
print(m.hexdigest())
# sha256 加密
m = hashlib.sha256()
m.update('admin'.encode('utf-8'))
print(m.hexdigest())
# sha384 加密
m = hashlib.sha384()
m.update('admin'.encode('utf-8'))
print(m.hexdigest())
# sha512 加密
# m = hashlib.sha512()
m.update('admin'.encode('utf-8'))
print(m.hexdigest())
configparser 模块 (配置文件)
直接上程序来说明比较清楚
# @Time : 2017/4/18 15:31 # @Author : Cui X # @File : configparser_mod.py import configparser class Config(object): """置文件操作""" def __init__(self, sections, prices): self.sections = sections self.prices = prices # 生成配置文件模板 @classmethod def config_create(cls): config = configparser.ConfigParser() config["db"] = {'db_host': '192.168.1.1', 'db_port': '3306', 'db_user': 'root', 'db_pass': 'password'} # 两种写法,上面是一种,下面是一种 config['concurrent'] = {} config['concurrent']['thread'] = '200' config['concurrent']['processor'] = '400' config.write(open('test.conf', 'w')) # 把数据读出来 @classmethod def config_read(cls): conf = configparser.ConfigParser() conf.read('test.conf') return conf # 判断数据是否在存在文件中 def config_judge(self): config = self.config_read() if self.sections in config.sections(): if self.prices in config[self.sections]: return True else: return False else: return False # 增加 def config_add(self, price): if self.config_judge() is False: config = self.config_read() if self.sections in config.sections(): config[self.sections][self.prices] = price config.write(open('test.conf', 'w')) print('数据写入成功') else: print('%s 不存在' % self.sections) else: print('数据已存在') def config_delete(self): if self.config_judge() is True: config = self.config_read() del config[self.sections][self.prices] config.write(open('test.conf', 'w')) print('数据删除成功') else: print('删除的值不存在') # 修改配置 def config_change(self, price): if self.config_judge() is True: config = self.config_read() config[self.sections][self.prices] = price config.write(open('test.txt', 'w')) print('%s %s 修改成功' % (self.sections, self.prices)) # 查询配置 def config_select(self): if self.config_judge() is True: config = self.config_read() select = config[self.sections][self.prices] print(select) @classmethod def show_sections_all(cls): config = cls.config_read() for s in config.sections(): print('[%s]' % s) for pr in config.options(s): print(pr, ' = ', config[s][pr]) if __name__ == '__main__': print("""\033[32;1m (0) 初始化配置文件 (1) 增加配置 (2) 删除配置 (3) 修改配置 (4) 查询配置 (5) 查看所有配置\033[0m """) while True: choose = input('选择操作项 >> ').strip() if choose.isdigit(): choose = int(choose) if choose < 5 and choose > 0: section = input('sections >> ').strip() item = input('item >> ').strip() conf = Config(section, item) if choose == 1: price = input('add item_price >> ').strip() conf.config_add(price) elif choose == 2: conf.config_delete() elif choose == 3: price = input('change item_price >> ').strip() conf.config_change(price) else: conf.config_select() elif choose == 0: affirm = input('yes/no ? >> ').strip() if affirm == 'yes': Config.config_create() print('\033[32;1m配置文件初始化成功\033[0m') else: print('\033[31;1m已取消操作\033[0m') elif choose == 5: Config.show_sections_all() else: print('\033[31;1m没有此项目\033[0m') else: print('\033[31;1m请正确输入\033[0m')
rediscluster
import threading from rediscluster import StrictRedisCluster from rediscluster import RedisCluster REDIS_NODES=[ {'host':'192.168.56.208','port':7000}, {'host':'192.168.56.208','port':7001}, {'host':'192.168.56.209','port':7002}, ] def cluster_conn(): conn = RedisCluster(startup_nodes=REDIS_NODES, decode_responses=True) return conn def redis_insert(): conn = cluster_conn() for i in range(200000): #conn.delete(i) # 删除key conn.set(i,'WWWWWWWW') # 添加key if __name__ == '__main__': for i in range(10): INSERT = threading.Thread(target=redis_insert) INSERT.start()
浙公网安备 33010602011771号