2023.12.24 python高级学习,模块和包,日志,时间操作,json模块

目录

模块和包

日志操作

时间操作

json模块


模块和包

__name__ 代码中一般都会写 if __name__ =='__main__' :

该判断,用来限定某些代码只在执行该模块代码的时候才执行

包:

包里一定要有个__init__.py文件

inti:初始化

模块和包:用来组织Python代码

  • 包 => 含有 __init__.py文件的文件夹

  • 模块 => py文件

  • 类 => class 【面向对象学习】

  • 函数(方法)=> def

以上均不能以数字开头,也不能和python内置的一切重名

# from 模块 import 函数
from os import listdir
ret = listdir()
print(ret)

# import 模块
import os
ret = os.listdir()
print(ret)

# 用 as关键字 起别名
import os as winos
ret = winos.listdir()
print(ret)

from os import listdir as win_listdir
ret = win_listdir()
print(ret)

日志操作

debug        调试消息

info        普通消息

warning        警告消息

error        错误消息

critical        严重错误

# import logger
# pip install loguru
from loguru import logger as log

# 日志文件名称
# {time} loguru包会自动填写文件创建的时间
# xxxx-xx-xx_xx-xx-xxxxxx 年 月 日 时 分 秒 微秒6位  【秒后3位的是毫秒 毫秒后3位是微妙】
logfile_path_str = './loguru_test_{time}.log'

# 日志保存,要先声明才有效
# log.add(logfile_path_str)
log.add(
    sink=logfile_path_str, # 日志文件名
    # 以下为可选参数
    rotation='200KB', # 设定日志大小, 200k一个文件
    compression='zip', # 设置压缩格式为zip
    retention='72h', # 每隔72小时清理一次日志
    serialize=True, # 默认为False,普通日志;True 把日志改成json格式
    encoding='utf8', # 声明日志文件的编码格式
    # level='WARNING' # 日志文件只记录WARNING及更严重级别的日志
)
""" 
1. 参数 rotation 
rotation='200KB', # 设定日志大小, 200k一个文件
rotation='14:00', # 每天中午14点创建新的日志文件
rotation='1 week', # 以周为单位,日志循环写入
2. 参数 compression='zip' # 支持多种压缩格式:
gz bz2 xz lzma tar tar.gz tar.bz2 tar.xz zip
3. level='WARNING' # 日志文件记录的级别,顺序如下:
DEBUG INFO SUCCESS WARNING ERROR CRITICAL
"""

生成的日志文件


# 自定义日志信息
log.debug('debug级别调试消息')
log.success('成功调用')
log.info('普通消息') # 常用
log.warning('警告消息')
log.error('错误消息')
log.critical('严重错误消息')

# 记录错误异常
try:
    print(5/0)
except:
    # 完整记录错误堆栈信息,显示内容和 traceback.format_exc() 一致
    log.exception('错误消息')

# 关闭控制台输出,且不写入日志文件
log.remove(handler_id=None)
log.info('这个信息不回显示,111')

时间操作

import time

# 停止n秒
print(time.sleep(3))

# 1695539421.6926203秒 起始时间是1970年1月1日0点(unix纪元)
print(time.time())  # 时间戳 1695539421.6926203
# print(time.ctime()) # Sun Sep 24 15:16:49 2023
print(time.strftime('%Y-%m-%d %H:%M:%S'))  # 2023-09-24 15:20:24
# 时间戳转日期,time.strftime函数多加一个参数
print(time.localtime())  # 不返回时间戳!
# time.struct_time(tm_year=2023, tm_mon=10, tm_mday=7, tm_hour=12, tm_min=0, tm_sec=35, tm_wday=5, tm_yday=280, tm_isdst=0)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
# 日期转时间戳
print(time.mktime(
    time.strptime(  # 注意区别 strptime strftime
        time.strftime('%Y-%m-%d %H:%M:%S'),  # 格式化的时间:2023-09-24 15:20:24
        '%Y-%m-%d %H:%M:%S'  # 指定格式
    )
))

json模块

# json是长得像字典的字符串,Python内置的json模块可以帮助我操作json
import json

my_dict = {'name': '职业法师刘海柱', 'age': 18}

# json.dumps():dict转json字符串,dumps==dump String
json_str = json.dumps(my_dict, ensure_ascii=False)
# ensure_ascii=False 是否使用ascii编码,默认为True
print(json_str, type(json_str)) # 双引号
print(my_dict, type(my_dict)) # 单引号

# json.loads():json字符串转dict,loads==load String
new_dict = json.loads(json_str)
print(new_dict, type(new_dict))

# json.dump() 将dict写入文件中,自动转换为json字符串
with open('./111.json', 'w', encoding='utf8') as f:
    json.dump(my_dict, f, ensure_ascii=False)

# json.load() 将文件中json字符串读取出来,返回dict
with open('./111.json', 'r', encoding='utf8') as f:
    new_dict2 = json.load(f)
    print(new_dict2, type(new_dict2))

你可能感兴趣的:(学习,python,开发语言,pycharm,服务器,大数据)