跳到主要内容
版本:0.17.0+

python howto

module:log

ref

module:hashlib

md5

implementation

import hashlib

def get_md5(s):

md5 = hashlib.md5()
md5.update(s.encode('utf-8'))
return md5.hexdigest()

ref

module:re

multi-line match

In fact, the real multi-line match means:

  1. allow match cross lines
  2. allow \n to be .

So, there is two flags to set: re.MULTIPLE and re.DOTALL like this: picture 82

ref:

module:typing

TypedDict NotRequired VS Optional

picture 1

Avoid using NotRequired and Optional picture 2

ref:

TypedDict self-reference

Here is what I want:

from typing import List, TypedDict

class TocItem(TypedDict):
level: int
title: str
children: List[TocItem]

However, it doesn't work since one property can not fetch the outer class.

There are at least two remedies, and I recommend to add one line in the top:

from __future__ import annotations

ref:

module:virtualenv

how to install and use virtualenv in python

# should use a local pip
pip install virtualenv

virtualenv YOUR/DIR

ref

conda

change default startup behavior in zsh

# .zshrc
# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
__conda_setup="$('/usr/local/anaconda3/bin/conda' 'shell.zsh' 'hook' 2> /dev/null)"
#if [ $? -eq 0 ]; then
# eval "$__conda_setup"
#else
if [ -f "/usr/local/anaconda3/etc/profile.d/conda.sh" ]; then
. "/usr/local/anaconda3/etc/profile.d/conda.sh"
else
export PATH="/usr/local/anaconda3/bin:$PATH"
fi
#fi
unset __conda_setup
# # <<< conda initialize <<<

how to print colorful text in terminal, mac and windows

use termcolor

pip install colorama
from colorama import init

# call this when init, so that all the ascii color would be displayed in windows
init()

ref:

how to install specific python in mac

  1. install homebrew
  2. brew install pyenv
  3. pyenv install VERSION
  4. pyenv global VERSION

how to print colored text to console/terminal in python

from termcolor import colored

# `colored` return a `Text` object, which can be called by `print()`
text = colored('Hello, World!', 'red', attrs=['reverse', 'blink', "bold"])
print(text)

⚠️ 不过注意,这些彩色实现,其实都是基于 ascii 码的,也就是 .\[\d+m这样的一个正则字符,并且不可以被 markdown 解析渲染。因此如果不单单是往控制台输出,还想保存成文件的话,则需要做相应处理。

  1. 最简单与直观的做法就是直接替换掉这些 ascii 标识,可以用sed很方便实现这一点,例如 python xxx | sed -r "s|.\[\d+m||g"
  2. 如果有多个输出目标,则可以考虑写两套文本生成算法,这个也比较推荐,尤其是生成 html 格式的彩色文本还是极其方便的,例如:<p style="color: XXX">YYY</p>
  3. 还有一种,专属于 markdown 的 ascii 码渲染方案,基于 github 的ascii2html仓库,不过看 issue,貌似功能不够稳健,然后是基于 c 的,我不怎么会运行……

ref: