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
✨✨ 非常方便的一下全给你列出来各种加密值:Hash 在线计算、md5 计算、sha1 计算、sha256 计算、sha512 计算 - 1024Tools
module:re
multi-line match
In fact, the real multi-line match means:
- allow match cross lines
- allow
\n
to be.
So, there is two flags to set: re.MULTIPLE
and re.DOTALL
like this:
ref:
re — Regular expression operations — Python 3.10.1 documentation
python - ignoring newline character in regex match - Stack Overflow
python - Regular expression matching a multiline block of text - Stack Overflow
python - What's the difference between re.DOTALL and re.MULTILINE? - Stack Overflow
module:typing
TypedDict NotRequired VS Optional
Avoid using NotRequired
and Optional
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
print in general operating system
use termcolor
print in windows
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
- install
homebrew
brew install pyenv
pyenv install VERSION
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 解析渲染。因此如果不单单是往控制台输出,还想保存成文件的话,则需要做相应处理。
- 最简单与直观的做法就是直接替换掉这些 ascii 标识,可以用
sed
很方便实现这一点,例如python xxx | sed -r "s|.\[\d+m||g"
。- 如果有多个输出目标,则可以考虑写两套文本生成算法,这个也比较推荐,尤其是生成 html 格式的彩色文本还是极其方便的,例如:
<p style="color: XXX">YYY</p>
- 还有一种,专属于 markdown 的 ascii 码渲染方案,基于 github 的
ascii2html
仓库,不过看 issue,貌似功能不够稳健,然后是基于 c 的,我不怎么会运行……
ref:
- A few of different solutions : How to Print Colored Text in Python - Studytonight