工程化

虚拟环境

python -m venv venv

linux 下激活

source venv/bin/activate

window 下激活

venv\Scripts\activate

退出虚拟环境

deactivate

conda

除了 python 官方自带的虚拟环境以外,我们还可以使用 conda 管理环境与依赖。

powershell 下无法使用 conda 解决办法,输入后重启命令窗口

conda init powershell

查看所有已存在环境

conda env list

创建环境

conda create -n llm
#指定python 版本
conda create -n llm python=3.11

激活环境与退出环境

conda activate llm
conda deactivate

删除环境

conda remove -n llm --all

jupyter使用conda环境

conda create -n my-conda-env
conda activate my-conda-env
conda install ipykernel
ipython kernel install --user --name=my-conda-env-kernel
jupyter notebook

依赖管理

  1. pip freeze > requirements.txt
  2. pip install pipreqspipreqs ./ --encoding=utf8 --force

log 记录

简单使用

import logging
logging.basicConfig(format='%(levelname)s - %(asctime)s - %(message)s',level=logging.DEBUG)
logging.warning('this is %s log','warning')
logging.info('info log')
logging.error('error log')

运行代码输出:

WARNING - 2023-04-21 10:27:38,631 - this is warning log
INFO - 2023-04-21 10:27:38,631 - info log
ERROR - 2023-04-21 10:27:38,631 - error log

yaml 配置 log

采用 YAML 格式,用于新的基于字典的方法

version: 1
formatters:
simple:
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
loggers:
app:
level: DEBUG
handlers: [console]
propagate: no
root:
level: DEBUG
handlers: [console]

使用如下:

import logging.config
import yaml
with open(file='conf/logging.yaml', mode='r', encoding='utf8') as file:
logging_yaml = yaml.load(stream=file, Loader=yaml.FullLoader)
logging.config.dictConfig(config=logging_yaml)
logger = logging.getLogger('app')
if __name__ == '__main__':
logger.warning('this is %s log', 'warning')
logger.info('info log')
logger.error('error log')

配置文件

环境变量中配置信息

import os
secret_key = os.environ.get('SECRET_KEY', 'jajajajhh')

yaml 配置文件

class Configure:
def __init__(self):
self.map_parameters = {}
self.cfg_file = os.path.abspath(os.path.join(os.path.dirname(__file__), ".conf/conf.yaml"))
self.init_local()
def init_local(self):
if os.path.exists(self.cfg_file):
with open(self.cfg_file, "r+", encoding="utf-8") as reader:
configure = yaml.load(reader, Loader=yaml.SafeLoader)
if "hbase" not in configure.keys():
raise ValueError("not hbase tables configure")
self.map_parameters["hbase"] = configure["hbase"]
self.map_parameters["hbase.common_param"] = configure["hbase"]["common_param"]
self.map_parameters["hbase.tables"] = configure["hbase"]["tables"]

使用如下:

conf = Configure()
hbase_param = conf.map_parameters["hbase"]