各种小技巧大杂烩
1. 跳到 conda 的根目录cd$(dirname$(dirname$(which conda)))2. 使用 git diff 直接比较两个文件gitdiff--no-index old_file new_file3. 查看 pkl 的内容importpickle as pkl with open(remember_use_rb.pkl,rb)as f: datapkl.load(f)print(data.keys())4. 可视化终端中的执行结果importsysimportosimportreimportsubprocess from PILimportImage, ImageDraw, ImageFont# 常见 16 色 亮色近似 xterm 默认ANSI_BASIC{30:(0,0,0),31:(205,49,49),32:(13,188,121),33:(229,229,16),34:(36,114,200),35:(188,63,188),36:(17,168,205),37:(229,229,229),90:(102,102,102),91:(241,76,76),92:(35,209,139),93:(245,245,67),94:(59,142,234),95:(214,112,214),96:(41,184,219),97:(255,255,255),}ANSI_ESCAPE_REre.compile(r\x1b\[[0-9;]*m|\x1b\].*?(?:\x07|\x1b\\))def _xterm256_color(n):ifn16: table[(0,0,0),(128,0,0),(0,128,0),(128,128,0),(0,0,128),(128,0,128),(0,128,128),(192,192,192),(128,128,128),(255,0,0),(0,255,0),(255,255,0),(0,0,255),(255,0,255),(0,255,255),(255,255,255),]returntable[n]ifn232: n -16r(n //36)*51g((n//6)%6)*51b(n%6)*51if r0and g0and b0:rgb5return(r,g,b)gray8(n-232)*10return(gray,gray,gray)def _apply_sgr(codes,fg,bg,bold):if not codes:return(229,229,229),(0,0,0),False if codes[0]:return(229,229,229),(0,0,0),False new_fg,new_bg,new_boldfg,bg,bold i0while ilen(codes):ccodes[i] if c0:new_fg,new_bg,new_bold(229,229,229),(0,0,0),False elif c1:new_boldTrue elif c22:new_boldFalse elif c39:new_fg(229,229,229)elif c49:new_bg(0,0,0)elif30c37or90c97:new_fgANSI_BASIC[c] elif40c47or100c107:idxc-10if c100else c-10-50new_bgANSI_BASIC[idx] elif c38and i2len(codes)and codes[i1]5:new_fg_xterm256_color(codes[i2])i2elif c48and i2len(codes)and codes[i1]5:new_bg_xterm256_color(codes[i2])i2i1return new_fg,new_bg,new_bold def parse_ansi(text):将带 ANSI 的文本解析为 [(text,fg,bg,bold),...] 行列表。 texttext.replace(\r\n,\n).replace(\r,\n)lines[] for raw_line in text.split(\n):fg,bg,bold(229,229,229),(0,0,0),False segments[] pos0for match in ANSI_ESCAPE_RE.finditer(raw_line):if match.start()pos:chunkraw_line[pos:match.start()] if chunk:segments.append((chunk,fg,bg,bold))seqmatch.group()ifseq.startswith(\x1b[): bodyseq[2:-1]codes[int(x)forxinbody.split(;)ifx.isdigit()]fg, bg, bold_apply_sgr(codes, fg, bg, bold)posmatch.end()ifposlen(raw_line): segments.append((raw_line[pos:],fg,bg,bold))lines.append(segments)returnlines def decode_output(data):按常见编码尝试解码避免系统默认 GBK 解码失败。ifnot data:returnifisinstance(data, str):returndataforencodingin(utf-8,gbk,cp936,latin-1): try:returndata.decode(encoding)except UnicodeDecodeError:continuereturndata.decode(utf-8,errorsreplace)def run_command(command):在伪终端中运行命令尽量保留彩色输出。envos.environ.copy()env[TERM]xterm-256colorenv[CLICOLOR_FORCE]1env[FORCE_COLOR]1env[COLORTERM]truecolorenv[PYTHONIOENCODING]utf-8# 始终按 bytes 捕获再手动解码避免 textTrue 走系统 GBKifsys.platformwin32:wrappedfchcp 65001 nul {command}resultsubprocess.run(wrapped,shellTrue,capture_outputTrue,envenv)else: try: resultsubprocess.run([script,-q,-c, command,/dev/null],capture_outputTrue,envenv,)except FileNotFoundError: resultsubprocess.run(command,shellTrue,capture_outputTrue,envenv)textdecode_output(result.stdout)or decode_output(result.stderr)ifnot text.strip(): text(No output)returntext def load_font(font_size14): font_paths[/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc,/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc,/System/Library/Fonts/PingFang.ttc,C:/Windows/Fonts/msyh.ttc,/usr/share/fonts/truetype/ubuntu/UbuntuMono-R.ttf,/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf,]forpathinfont_paths:ifos.path.exists(path): try:returnImageFont.truetype(path, font_size,encodingunic)except OSError:continuereturnImageFont.load_default()def _segment_width(draw, text, font, bold):ifnot text:return0ifbold:# 粗体近似重复绘制偏移宽度略增returndraw.textlength(text,fontfont)1returndraw.textlength(text,fontfont)def _draw_segment(draw, x, y, text, fg, bg, font, bold):ifnot text:returnx bboxdraw.textbbox((x,y),text,fontfont)draw.rectangle(bbox,fillbg)if bold:draw.text((x,y),text,fillfg,fontfont)draw.text((x1,y),text,fillfg,fontfont)else:draw.text((x,y),text,fillfg,fontfont)return x_segment_width(draw,text,font,bold)def command_to_image(command,output_fileoutput.png):rawrun_command(command)parsed_linesparse_ansi(raw)font_size14fontload_font(font_size)padding10line_heightfont_size4# 先用临时画布测量宽度 measure_imgImage.new(RGB,(1,1))measure_drawImageDraw.Draw(measure_img)max_width0forsegmentsinparsed_lines: line_wsum(_segment_width(measure_draw, t, font, b)fort, _, _, binsegments)max_widthmax(max_width, line_w)heightmax(1, len(parsed_lines))* line_height padding *2imgImage.new(RGB,(int(max_width) padding *2, height),color(0,0,0))drawImageDraw.Draw(img)ypaddingforsegmentsinparsed_lines: xpaddingfortext, fg, bg, boldinsegments: x_draw_segment(draw, x, y, text, fg, bg, font, bold)yline_height img.save(output_file)print(f图片已保存: {output_file})if__name____main__:iflen(sys.argv)2: print(用法: python photolizy.py 你的命令 [输出文件名])print(示例: python photolizy.py ls --coloralways my_output.png)sys.exit(1)cmdsys.argv[1]outsys.argv[2]iflen(sys.argv)2elseoutput.pngcommand_to_image(cmd, out)# 记得加上 --coloralways5. tar 指定文件夹进行打包# 打包多个具体文件tar-cvfarchive.tar file1.txt file2.txt file3.txt# 打包所有 .txt 文件tar-cvfarchive.tar *.txt# 打包多个目录tar-cvfarchive.tar dir1/ dir2/ dir3/