Skip to main content

utox

个人 Python 工具库:日志、时间、配置、文件读写、装饰器等常用功能。

安装

pip install utox

如需使用 read_file 的 pydantic 模型解析能力,额外安装:

pip install utox[pydantic]

快速开始

日志

from utox import newLog, DEBUG

log = newLog("myapp")            # 控制台彩色输出,默认 INFO 级别
log.info("hello %s", "world")

log = newLog("myapp", level=DEBUG)          # 级别常量(无需 import logging)
log = newLog("myapp", level="DEBUG")        # 也支持级别名字符串,大小写不敏感
log = newLog("myapp", enable_file=True)     # 加文件输出

文件默认写入项目根目录的 logs/ 下,按天命名(2026_08_15.log);午夜自动切换到新日期的文件(长驻进程跨天运行也能正确分文件),仅保留最近 30 天。单文件超过 max_bytes(默认不限)时当天文件自动轮转为 .1/.2/... 后缀:

log = Log("myapp", enable_file=True,
          backup_days=30, max_bytes=50 * 1024 * 1024, max_backups=10)

异常堆栈:

try:
    ...
except Exception:
    log.exception("任务失败")      # ERROR 级别,附带完整堆栈

JSON 结构化日志(供 ELK 等采集系统解析,extra= 字段会合并进 JSON):

log = newLog("myapp", enable_file=True, json_format=True)
log.info("用户登录", extra={"user_id": 42})
# 文件里每行:{"time": "...", "level": "INFO", "logger": "myapp", "message": "用户登录", "user_id": 42}

时间

from utox import now_ts, now_ms, now_str, ts_to_str, ms_to_str, str_to_ts

now_ts()                            # 当前 Unix 时间戳(秒)
now_ms()                            # 毫秒时间戳(与 OKX 返回格式一致)
now_str()                           # "2026-08-16 00:30:00"(东八区)
ts_to_str(1710478800)               # 秒 -> 东八区字符串
ms_to_str(1710478800000)            # 毫秒 -> 东八区字符串
str_to_ts("2024-03-15 13:00:00")    # 东八区字符串 -> 秒

# 旧接口仍然可用(等价于新接口)
from utox import str2timestamp, timestamp2str, seconds_since_midnight
ts = str2timestamp("2024-03-15 13:00:00")   # -> 1710478800
s = timestamp2str(ts)                        # -> "2024-03-15 13:00:00"
seconds_since_midnight("2024-03-15 13:00:00")  # -> 46800(当天已过的秒数,delta_day 的语义化别名)

所有时间均为固定东八区(UTC+8,无夏令时),不随系统时区变化。

ini 配置

from utox import IniUtil

ini = IniUtil("./conf.ini")
ini.get_value("section", "key")        # 字符串
ini.get_int("section", "num")          # 整数
ini.get_bool("section", "flag")        # 布尔(yes/no、true/false、1/0)
ini.set_value("section", "key", "value")
ini.delete("section", "key")           # 删除配置项(不传 option 删整个 section)
ini.as_dict()                          # 全部配置 -> {section: {option: value}}

文件读写

from utox import read_file, write_file

write_file("data.json", '{"a": 1}')
read_file("data.json")          # -> {"a": 1}

# 传入 pydantic 模型类可自动校验
read_file("data.json", MyModel)

装饰器

from utox import profile, time_it, retry, memoize

@time_it
def slow_func():
    ...

@profile()
def heavy_func():
    ...

@retry(max_retries=3, delay=1, backoff=2, logger=log)   # 失败自动重试(指数退避)
def unstable_api():
    ...

@memoize(ttl=60)               # 结果缓存 60 秒;不传 ttl 则永久缓存
def expensive_query(user_id):
    ...

常用工具

from utox import is_empty, is_not_empty, pre_condition, to_response

is_empty("")        # True
is_not_empty("x")   # True
pre_condition(x > 0, "x 必须大于 0")   # 不满足抛 ValueError
to_response(0, "ok", data)            # {"code": 0, "msg": "ok", "data": data}

API 一览

模块 内容
utox.log Log / newLog:彩色控制台 + 按天滚动文件日志(北京时间,可叠加单文件大小上限);DEBUG/INFO/WARNING/ERROR/CRITICAL 级别常量;exception() 堆栈日志、json_format 结构化日志
utox.timeutil now_ts/now_ms/now_str/ts_to_str/ms_to_str/str_to_ts(固定东八区);seconds_since_midnight;旧接口 str2timestamp/timestamp2str/delta_day
utox.iniutil IniUtil:ini 配置读写(get_value/get_int/get_float/get_bool/set_value/delete/as_dict)
utox.fileutil read_file / write_file(支持 pydantic 可选解析)
utox.annotationutil profile / time_it / retry(重试)/ memoize(缓存)装饰器
utox.util 空值判断、条件断言、项目根目录探测、区间重叠判断等

开发

pip install -e .[test]
pytest

License

Apache-2.0

Metadata

Release files for utox 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for utox 0.1.3
File Size Uploaded Provenance Actions
utox-0.1.3.tar.gz 28.3 kB Without provenance Details for utox-0.1.3.tar.gz

Release files / utox-0.1.3.tar.gz

Download URL utox-0.1.3.tar.gz
Size 28.3 kB
Tags Source
SHA-256 checksum
How to use checksums
2cbbabf873ee77555ba01bc80108d379b96e9de5b8372a91402b03347fbd10f6
BLAKE2b-256 checksum
How to use checksums
15460128770df4c140ae02602fe335042df281716f266f245b0b9866234e2953
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.7

Security for utox 0.1.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page