Colderleo's blog Colderleo's blog
首页
Linux
C++
Python
前端
工具软件
mysql
索引
关于
GitHub (opens new window)

Colder Leo

热爱代码的打工人
首页
Linux
C++
Python
前端
工具软件
mysql
索引
关于
GitHub (opens new window)
  • 1-django使用
  • centos部署Nginx+uwsgi+django - blog
  • django-admin完全自定义某个模块的页面
  • easy_select2 编辑页面添加外键选择搜索
  • 使用vscode开发python
  • python自定义异常处理with,上下文context管理器
  • python读写excel,xlsx 模块选择
  • python多线程多进程协程
  • TemporaryFile
  • threading用法
  • ubantu设置python优先级
  • conda anacodna 命令行用法
  • 我写的常用工具函数
  • 0-python常用函数
  • smtp发送邮件
  • pandas用法
  • datetime类,时间差
  • format
  • enumerate遍历数组时获取index
  • argv
  • generator 生成器
  • GIL锁、多线程
  • linux用源文件安装python3
  • list sort排序
  • logging日志
  • mulitporcessing共享变量
  • OrderedDict
  • path
  • pip用法
  • pymysql用法 - python连接mysql
  • python bash解释器,脚本前两行,
  • python docstring格式 PEP 257
  • python logging获取logger信息
  • python交互式窗口如何进行多行输入
  • virtualenv用法
  • 标准差
  • 单例模式
  • 函数中定义static变量
  • 切片
  • 去掉字符串中emoji字符
  • 去掉字符串中的空行
  • 全局变量、global和nonlocal
  • 文字识别pytesseract
  • 析构函数和del
  • 用python制作游戏外挂
  • 正则表达式,函数替换字符串
  • 装饰器
  • pycharm中运行pyqt时不报错
  • python 写文件
  • Python
gaoliu
2021-10-06

我写的常用工具函数

# json文件读写

python中的字典可以直接保存为json文件,也可以读取python文件load之后变成字典对象

如果字典中字符串含有中文,在调用json.dum时,会默认被保存成\u开头的编码,此时需要在参数中加上ensure_ascii=False。读取的时候不用管,直接读就是正常的。indent = 4表示json保存的时候格式化,缩进为4个空格。

# tools.py

import logging, coloredlogs
from functools import wraps
import json

# 使用:  from tools import config, saveConfig, logger, printExcept


# config.json文件
with open('config.json','r',encoding='utf-8') as f:
    config = json.load(f)

def saveConfig(confDict):
    with open('config.json', 'w',encoding='utf-8') as f:
        json.dump(confDict, f, ensure_ascii=False, indent=4)
        
        

# 多次尝试执行某个函数,
# 该函数返回bool类型,True表示成功。False表示失败
# 多次尝试,执行成功立刻返回Ture,重试多次都失败则返回False
def tryExecTimes(func, times:int, *args, **kwargs)->bool:
    for i in range(times):
        ret = func(*args, **kwargs)
        if ret:
            return True
    return False




# color logging
class _logger:
    def __init__(self):
        coloredlogs.DEFAULT_FIELD_STYLES = \
            {'asctime': {'color': 'green'},
                'hostname': {'color': 'magenta'},
                'levelname': {'color': 'black', 'bold': True},
                'module': {'color': 'blue'},
                'name': {'color': 'blue'},
                'programname': {'color': 'cyan'}
            }
        coloredlogs.DEFAULT_LEVEL_STYLES = \
            {'critical': {'bold': True, 'background':'red'},
                'debug': {'color': 'green'},
                'error': {'color': 'red'},
                'info': {},
                'notice': {'color': 'magenta'},
                'spam': {'color': 'green', 'faint': True},
                'success': {'color': 'green', 'bold': True},
                'verbose': {'color': 'blue'},
                'warning': {'color': 'yellow'}
            }

        self.logger = logging.getLogger('main')
        # coloredlogs.install(level='INFO', fmt='%(asctime)s,%(msecs)03d %(levelname)s %(message)s')  不要删
        coloredlogs.install(level='INFO', fmt='%(asctime)s, %(levelname)s, %(module)s[%(lineno)d] %(message)s')

        # Some examples.
        # logger.debug("this is a debugging message")
        # logger.info("this is an informational message")
        # logger.warning("this is a warning message")
        # logger.error("this is an error message")
        # logger.critical("this is a critical message")

logger = _logger().logger




# wrap一段代码,如果有异常则打印异常信息,然后继续运行。
def printExcept(func):
    @wraps(func)
    def inner(*args, **kwargs):
        try:
            ret = func(*args, **kwargs)
            return ret
        except Exception as e:
            print("func '{}' error: {}".format(func.__name__, str(e)))
    return inner


def wrapperTpl(func):
    @wraps(func)
    def inner(*args, **kwargs):
        '''在执行目标函数之前要执行的内容'''
        ret = func(*args, **kwargs)
        '''在执行目标函数之后要执行的内容'''
        return ret
    return inner
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
编辑 (opens new window)
上次更新: 2021/10/11, 12:43:58
conda anacodna 命令行用法
0-python常用函数

← conda anacodna 命令行用法 0-python常用函数→

最近更新
01
通过模板实现结构体成员拷贝-按成员名匹配
05-07
02
c++17通过模板获取类成员的个数
05-01
03
avx-sse切换惩罚
04-30
更多文章>
Theme by Vdoing | Copyright © 2019-2023 Colder Leo | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×