羊城交通台,闽剧加演,上海沪剧院
包:文件夹下具有__init__.py文件就是一个包,包用来管理多个模块
包的结构如下:
bake ├── __init__.py ├── api ├── __init__.py ├── policy.py └── versions.py ├── cmd ├── __init__.py └── manage.py └── db ├── __init__.py └── models.py
在bake的同级创建一个test.py导入policy.py:
import bake.api.policy bake.api.policy.get() #导入的名字太长了,可以起别名 import bake.api.policy as p p.get() #from 导入在__init__.py修改 from . import policy #我们需要在policy文件中向sys.path添加了当前的路径 import os import sys sys.path.insert(os.path.dirname(__file__)) #print(__file__)查看一下 #使用__all__,在__init__.py中 __all__ = ["policy"] #或 from . import policy
总结:
import 包.包.包
from 包.包.包 import 模块
路径:
绝对:从在外层开始导入
相对:从当前开始(.)导入或者从父级(..)导入
使用相对路径时必须在包的最外层且同级
from 包 import *
需要在__init__.py做操作
python2:import文件夹(没有__init__.py)会报错
python3:import文件夹(没有__init__.py)不会报错
logging模块用于记录软件的各种状态,交易记录,错误记录,登录记录……
import logging logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
默认情况下python的logging模块将日志打印到了标准输出中,且只显示了大于等于warning级别的日志,证明默认的级别为warning
日志级别:critical > error > warning > info > debug
只能写入日志,不能公屏输出
import logging logging.basicconfig(level = logging.debug, format = '%(astime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s', datefmt = '%y-%m-%d %h:%m:%s', filename = 'test.log', filemode = 'a') dic = {"key":123} logging.debug(dic) num = 100 logging.info(f"用户余额:{num - 50}") try: num = int(input("请输入数字:")) except exception as e: logging.warning("e") logging.error('error message') logging.critical('critical message')
basicconfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:
format参数中可能用到的格式化串:
import logging logger = logging.getlogger() # 创建一个logger fh = logging.filehandler('test.log',mode="a",encoding='utf-8') # 文件 ch = logging.streamhandler() # 屏幕 formatter = logging.formatter('%(asctime)s - %(name)s - %(filename)s - [line:%(lineno)d] - %(levelname)s - %(message)s') # 将屏幕和文件都是用以上格式 logger.setlevel(logging.debug) # 设置记录级别 fh.setformatter(formatter) # 使用自定义的格式化内容 ch.setformatter(formatter) logger.addhandler(fh) #logger对象可以添加多个fh和ch对象 logger.addhandler(ch) logger.debug('logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message')
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Python 实现将numpy中的nan和inf,nan替换成对应的均值
python爬虫把url链接编码成gbk2312格式过程解析
网友评论