6.824/6.5840 的Debugging by Pretty Printing配置

TA的原文在:Debugging by Pretty Printing (josejg.com)

为了在WSL2中配置好打印运行日志,我可是忙活了一下午。可恶的log配置

首先是安装rich库Textualize/rich: Rich is a Python library for rich text and beautiful formatting in the terminal. (github.com)

python -m pip install rich

然后我发现我的pip命令报错了

$ python -m pip install rich
/usr/bin/python: No module named pip

尝试了多种方法依然失败,最后采用的方法是如下

先更新自己的系统安装包

sudo apt-get update
sudo apt-get upgrade

然后重新安装一遍pip

sudo apt install python3-pip

如果你没有遇到pip的问题,成功安装好了rich库,进行下一步

1. 准备好python3解释器

2.打开终端,输入which python3 复制解释器地址

3.在你需要执行的python文件最上方加上 #! python解释器地址

#!/usr/bin python3

 其实这么写可能会有问题,我就碰到了如下问题

-bash: /usr/bin/dtest: /usr/bin: bad interpreter: Permission denied

如果你也碰到了类似的问题,把上述语句改为

#!/usr/bin/env python3

4.修改当前需要执行的文件的权限 chmod +x xxx.py

例如

chmod +x dtest.py
chmod +x dslog.py

这句命令的意思是为xxx.py这个文件添加可执行权限

执行完上述命令后我们可以查看一下是否成功修改权限

5.复制当前文件到python解释器的bin/文件目录下

我的Python解释器目录在/usr/bin,目录的后缀/xxx是把xxx.py文件复制到这个文件夹中并且改名为xxx。我这里就是把dtest.py复制到了/usr/bin后改名为dtest

sudo cp dtest.py /usr/bin/dtest
sudo cp dslog.py /usr/bin/dslog

6.终端直接输入你的python文件名就可以看到运行结果了

如果你的WSL2没有安装过Python的库,一般还会报错

手动安装typer这个库就行

7.最后运行结果如下

dslog.py文件如下

#!/usr/bin/env python3
import sys
import shutil
from typing import Optional, List, Tuple, Dictimport typer
from rich import print
from rich.columns import Columns
from rich.console import Console
from rich.traceback import install# fmt: off
# Mapping from topics to colors
TOPICS = {"TIMR": "#9a9a99","VOTE": "#67a0b2","LEAD": "#d0b343","TERM": "#70c43f","LOG1": "#4878bc","LOG2": "#398280","CMIT": "#98719f","PERS": "#d08341","SNAP": "#FD971F","DROP": "#ff615c","CLNT": "#00813c","TEST": "#fe2c79","INFO": "#ffffff","WARN": "#d08341","ERRO": "#fe2626","TRCE": "#fe2626",
}
# fmt: ondef list_topics(value: Optional[str]):if value is None:return valuetopics = value.split(",")for topic in topics:if topic not in TOPICS:raise typer.BadParameter(f"topic {topic} not recognized")return topicsdef main(file: typer.FileText = typer.Argument(None, help="File to read, stdin otherwise"),colorize: bool = typer.Option(True, "--no-color"),n_columns: Optional[int] = typer.Option(None, "--columns", "-c"),ignore: Optional[str] = typer.Option(None, "--ignore", "-i", callback=list_topics),just: Optional[str] = typer.Option(None, "--just", "-j", callback=list_topics),
):topics = list(TOPICS)# We can take input from a stdin (pipes) or from a fileinput_ = file if file else sys.stdin# Print just some topics or exclude some topics (good for avoiding verbose ones)if just:topics = justif ignore:topics = [lvl for lvl in topics if lvl not in set(ignore)]topics = set(topics)console = Console()width = console.size.widthpanic = Falsefor line in input_:try:time, topic, *msg = line.strip().split(" ")# To ignore some topicsif topic not in topics:continuemsg = " ".join(msg)# Debug calls from the test suite aren't associated with# any particular peer. Otherwise we can treat second column# as peer idif topic != "TEST":i = int(msg[1])# Colorize output by using rich syntax when neededif colorize and topic in TOPICS:color = TOPICS[topic]msg = f"[{color}]{msg}[/{color}]"# Single column printing. Always the case for debug stmts in testsif n_columns is None or topic == "TEST":print(time, msg)# Multi column printing, timing is dropped to maximize horizontal# space. Heavylifting is done through rich.column.Columns objectelse:cols = ["" for _ in range(n_columns)]msg = "" + msgcols[i] = msgcol_width = int(width / n_columns)cols = Columns(cols, width=col_width - 1, equal=True, expand=True)print(cols)except:# Code from tests or panics does not follow format# so we print it as isif line.startswith("panic"):panic = True# Output from tests is usually important so add a# horizontal line with hashes to make it more obviousif not panic:print("#" * console.width)print(line, end="")if __name__ == "__main__":typer.run(main)

dtest.py内容如下

#!/usr/bin/env python3import itertools
import math
import signal
import subprocess
import tempfile
import shutil
import time
import os
import sys
import datetime
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
from dataclasses import dataclass
from pathlib import Path
from typing import List, Optional, Dict, DefaultDict, Tupleimport typer
import rich
from rich import print
from rich.table import Table
from rich.progress import (Progress,TimeElapsedColumn,TimeRemainingColumn,TextColumn,BarColumn,SpinnerColumn,
)
from rich.live import Live
from rich.panel import Panel
from rich.traceback import installinstall(show_locals=True)@dataclass
class StatsMeter:"""Auxiliary classs to keep track of online stats including: count, mean, varianceUses Welford's algorithm to compute sample mean and sample variance incrementally.https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#On-line_algorithm"""n: int = 0mean: float = 0.0S: float = 0.0def add(self, datum):self.n += 1delta = datum - self.mean# Mk = Mk-1+ (xk – Mk-1)/kself.mean += delta / self.n# Sk = Sk-1 + (xk – Mk-1)*(xk – Mk).self.S += delta * (datum - self.mean)@propertydef variance(self):return self.S / self.n@propertydef std(self):return math.sqrt(self.variance)def print_results(results: Dict[str, Dict[str, StatsMeter]], timing=False):table = Table(show_header=True, header_style="bold")table.add_column("Test")table.add_column("Failed", justify="right")table.add_column("Total", justify="right")if not timing:table.add_column("Time", justify="right")else:table.add_column("Real Time", justify="right")table.add_column("User Time", justify="right")table.add_column("System Time", justify="right")for test, stats in results.items():if stats["completed"].n == 0:continuecolor = "green" if stats["failed"].n == 0 else "red"row = [f"[{color}]{test}[/{color}]",str(stats["failed"].n),str(stats["completed"].n),]if not timing:row.append(f"{stats['time'].mean:.2f} ± {stats['time'].std:.2f}")else:row.extend([f"{stats['real_time'].mean:.2f} ± {stats['real_time'].std:.2f}",f"{stats['user_time'].mean:.2f} ± {stats['user_time'].std:.2f}",f"{stats['system_time'].mean:.2f} ± {stats['system_time'].std:.2f}",])table.add_row(*row)print(table)def run_test(test: str, race: bool, timing: bool):test_cmd = ["go", "test", f"-run={test}"]if race:test_cmd.append("-race")if timing:test_cmd = ["time"] + cmdf, path = tempfile.mkstemp()start = time.time()proc = subprocess.run(test_cmd, stdout=f, stderr=f)runtime = time.time() - startos.close(f)return test, path, proc.returncode, runtimedef last_line(file: str) -> str:with open(file, "rb") as f:f.seek(-2, os.SEEK_END)while f.read(1) != b"\n":f.seek(-2, os.SEEK_CUR)line = f.readline().decode()return line# fmt: off
def run_tests(tests: List[str],sequential: bool       = typer.Option(False,  '--sequential',      '-s',    help='Run all test of each group in order'),workers: int           = typer.Option(1,      '--workers',         '-p',    help='Number of parallel tasks'),iterations: int        = typer.Option(10,     '--iter',            '-n',    help='Number of iterations to run'),output: Optional[Path] = typer.Option(None,   '--output',          '-o',    help='Output path to use'),verbose: int           = typer.Option(0,      '--verbose',         '-v',    help='Verbosity level', count=True),archive: bool          = typer.Option(False,  '--archive',         '-a',    help='Save all logs intead of only failed ones'),race: bool             = typer.Option(False,  '--race/--no-race',  '-r/-R', help='Run with race checker'),loop: bool             = typer.Option(False,  '--loop',            '-l',    help='Run continuously'),growth: int            = typer.Option(10,     '--growth',          '-g',    help='Growth ratio of iterations when using --loop'),timing: bool           = typer.Option(False,   '--timing',          '-t',    help='Report timing, only works on macOS'),# fmt: on
):if output is None:timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")output = Path(timestamp)if race:print("[yellow]Running with the race detector\n[/yellow]")if verbose > 0:print(f"[yellow] Verbosity level set to {verbose}[/yellow]")os.environ['VERBOSE'] = str(verbose)while True:total = iterations * len(tests)completed = 0results = {test: defaultdict(StatsMeter) for test in tests}if sequential:test_instances = itertools.chain.from_iterable(itertools.repeat(test, iterations) for test in tests)else:test_instances = itertools.chain.from_iterable(itertools.repeat(tests, iterations))test_instances = iter(test_instances)total_progress = Progress("[progress.description]{task.description}",BarColumn(),TimeRemainingColumn(),"[progress.percentage]{task.percentage:>3.0f}%",TimeElapsedColumn(),)total_task = total_progress.add_task("[yellow]Tests[/yellow]", total=total)task_progress = Progress("[progress.description]{task.description}",SpinnerColumn(),BarColumn(),"{task.completed}/{task.total}",)tasks = {test: task_progress.add_task(test, total=iterations) for test in tests}progress_table = Table.grid()progress_table.add_row(total_progress)progress_table.add_row(Panel.fit(task_progress))with Live(progress_table, transient=True) as live:def handler(_, frame):live.stop()print('\n')print_results(results)sys.exit(1)signal.signal(signal.SIGINT, handler)with ThreadPoolExecutor(max_workers=workers) as executor:futures = []while completed < total:n = len(futures)if n < workers:for test in itertools.islice(test_instances, workers-n):futures.append(executor.submit(run_test, test, race, timing))done, not_done = wait(futures, return_when=FIRST_COMPLETED)for future in done:test, path, rc, runtime = future.result()results[test]['completed'].add(1)results[test]['time'].add(runtime)task_progress.update(tasks[test], advance=1)dest = (output / f"{test}_{completed}.log").as_posix()if rc != 0:print(f"Failed test {test} - {dest}")task_progress.update(tasks[test], description=f"[red]{test}[/red]")results[test]['failed'].add(1)else:if results[test]['completed'].n == iterations and results[test]['failed'].n == 0:task_progress.update(tasks[test], description=f"[green]{test}[/green]")if rc != 0 or archive:output.mkdir(exist_ok=True, parents=True)shutil.copy(path, dest)if timing:line = last_line(path)real, _, user, _, system, _ = line.replace(' '*8, '').split(' ')results[test]['real_time'].add(float(real))results[test]['user_time'].add(float(user))results[test]['system_time'].add(float(system))os.remove(path)completed += 1total_progress.update(total_task, advance=1)futures = list(not_done)print_results(results, timing)if loop:iterations *= growthprint(f"[yellow]Increasing iterations to {iterations}[/yellow]")else:breakif __name__ == "__main__":typer.run(run_tests)

By the way,dtest的运行方式如下

dtest --help #查看运行参数dtest -n 10(运行一百遍) -p 5(五个并发的运行测试加快运行速率) -s(顺序执行) 
-v(将Debug打印到log) 3A(测试点名称)

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/43807.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

用于视频生成的扩散模型

学习自https://lilianweng.github.io/posts/2024-04-12-diffusion-video/ 文章目录 3D UNet和DiTVDMImagen VideoSora 调整图像模型生成视频Make-A-Video&#xff08;对视频数据微调&#xff09;Tune-A-VideoGen-1视频 LDMSVD稳定视频扩散 免训练Text2Video-ZeroControlVideo 参…

需求分析|泳道图 ProcessOn教学

文章目录 1.为什么使用泳道图2.具体例子一、如何绘制确定好泳道中枢的角色在中央基于事实来绘制过程不要纠结美观先画主干处理流程再画分支处理流程一个图表达不完&#xff0c;切分子流程过程数不超25 &#xff0c;A4纸的幅面处理过程过程用动词短语最后美化并加上序号酌情加上…

leetcode hot 100 刷题记录

题目300&#xff1a;最长递增子序列&#xff08;NO&#xff09; 解题思路&#xff1a;动态规划&#xff0c;就是dp[i]的运用&#xff0c;这里dp[i]表示第i个元素为结尾的最长子序列。 给你一个整数数组 nums &#xff0c;找到其中最长严格递增子序列的长度。 子序列 是由数组…

后端——全局异常处理

一、老办法try-catch 当我们执行一些错误操作导致程序报错时&#xff0c;程序会捕捉到异常报错&#xff0c;这个异常会存在一个Exception对象里 那我们在spring boot工程开发时&#xff0c;当我们执行一个sql查询时报错了&#xff0c;那就会从最底层的Mapper层捕捉到Exceptio…

Android应用程序调试Logcat的使用

Android的程序调试主要使用Logcat进行&#xff0c;本节主要介绍Logcat的使用。 开启调试模式 使用Android Studio进行程序调试&#xff0c;首先需要连接虚拟Android设备或真实Android设备&#xff0c;设备上需要启用调试功能。 虚拟Android设备默认情况下会启用调试功能。对…

C++ 入门03:函数与作用域

往期回顾&#xff1a; C 入门01&#xff1a;初识 C-CSDN博客C 入门02&#xff1a;控制结构和循环-CSDN博客 一、前言 在前面的文章学习中&#xff0c;我们了解了C语言的基础&#xff0c;包括如何定义变量来存储数据&#xff0c;以及如何利用输入输出流实现程序与用户之间的无缝…

华为机考真题 -- 找朋友

题目描述: 在学校中,N 个小朋友站成一队, 第 i 个小朋友的身高为 height[i],第 i 个小朋友可以看到的第一个比自己身高更高的小朋友 j,那么 j 是 i 的好朋友(要求 j >i)。请重新生成一个列表,对应位置的输出是每个小朋友的好朋友位置,如果没有看到好朋友,请在该位置…

微软清华提出全新预训练范式,指令预训练让8B模型实力暴涨!实力碾压70B模型

现在的大模型训练通常会包括两个阶段&#xff1a; 一是无监督的预训练&#xff0c;即通过因果语言建模预测下一个token生成的概率。该方法无需标注数据&#xff0c;这意味着可以利用大规模的数据学习到语言的通用特征和模式。 二是指令微调&#xff0c;即通过自然语言指令构建…

Python面试题:请解释什么是鸭子类型(duck typing)?

鸭子类型&#xff08;Duck Typing&#xff09;是一种动态类型语言中的概念&#xff0c;它基于对象的行为&#xff08;方法和属性&#xff09;而不是其实际类型进行判断。这个概念源自詹姆斯惠特科姆赖利的谚语&#xff1a; “如果它走起来像鸭子&#xff0c;叫起来像鸭子&#…

通过高德地图 JS API实现单击鼠标进行标注

效果图: 核心代码: <template><a-modal title="选择地图所在位置" :width="width" :visible="visible" @ok="handleOk" @cancel="handleCancel" cancelText="关闭"><div class="location-…

场外期权有交割日吗?场外期权应该怎么交割?

今天带你了解场外期权有交割日吗&#xff1f;场外期权应该怎么交割&#xff1f;场外个股期权是一种非标准化的金融衍生品&#xff0c;它允许投资者在未来某一特定日期以特定价格买入或卖出某一特定股票。 交割日就是买卖双方进行交割的日期,期权合约具有到期日,到期日的后一天…

WEB安全-文件上传漏洞

1 需求 2 接口 3 MIME类型 在Web开发中&#xff0c;MIME&#xff08;Multipurpose Internet Mail Extensions&#xff09;类型用于标识和表示文档的格式。这些类型在HTTP请求和响应头中扮演着重要的角色&#xff0c;告诉浏览器如何解释和处理接收到的资源12。 以下是一些Web开发…

ChatGPT:Java Stream 的疑问

ChatGPT&#xff1a;Java Stream 的疑问 解释一下 List<SupplierVm> collect tSupplierPage.getRecords().stream().map(item ->{SupplierVm supplierVm new SupplierVm();BeanUtils.copyProperties(item, supplierVm);return supplierVm;}).collect(Collectors.to…

【JavaScript】具有 iterable 接口的数据结构

具有 iterable 接口的数据结构指的是可以通过迭代器&#xff08;Iterator&#xff09;访问其成员的数据结构。在 JavaScript 中&#xff0c;具有 iterable 接口的数据结构包括数组&#xff08;Array&#xff09;、字符串&#xff08;String&#xff09;、Set、Map 等。这些数据…

C电池 和 D 电池的作用和类型详解及其之间的区别

C 和 D 电池是我们日常生活中必不可少的部件。它们通常用于高功率设备。例如手电筒和玩具。 D 型电池和 C 型电池是两种常见的电池类型。它们是一次性圆柱形电池。您可以在很多设备上使用它们。虽然它们有很多相似之处&#xff0c;但它们也有不同的特点。这些特点使它们适合某…

如何用qq邮箱注册outlook邮箱

&#x1f4d1;打牌 &#xff1a; da pai ge的个人主页 &#x1f324;️个人专栏 &#xff1a; da pai ge的博客专栏 ☁️宝剑锋从磨砺出&#xff0c;梅花香自苦寒来 ​ 目录 第一步输入qq邮箱 第二步…

数据类型及数据块认知

西门子STEP7编程语言 梯形图(LAD) 功能块图(FBD) 语句表(STL) 其中梯形图和功能块图可以相互转换 CPU常用数据区 信号输入区 I 信号输出区 Q 程序中表现形式&#xff0c;IX.X/QX.X;IWX/QWX-访问的是CPU输出输入过程映像区 另一种形式IWX:P/QWX:P-访问的是信号端口地址&#xf…

深度整合全球资源,分贝通打造高效、合规的海外差旅管理平台

在全球化商业活动的背景下,中国企业出海已成为常态。然而,随着海外差旅市场的全面增长,企业在海外支出管理上面临诸多挑战。据2023年数据显示,分贝通出海差旅业务GMV同比增长高达500倍,这一增长背后隐藏着企业对于更省钱、更高效管控方式的迫切需求。 面对与日俱增的开支,企业开…

js对象的方法速览---数组的静态方法,实例方法和属性合集,各包含一个示例

tip&#xff1a; 本文仅作为查找和基本使用的展示&#xff0c;需要深入了解这些方法的使用请参考&#xff1a;Object - JavaScript | MDN (mozilla.org) 可以通过目录快速锁定需要查找的方法和查看它的使用 目录 tip&#xff1a; 新建一个对象 实例属性 实例方法 hasOwn…

Websocket 替代方案:如何使用 Firestore 监听实时事件

大家好,我是CodeQi! 一位热衷于技术分享的码仔。 ​在现代 Web 开发中,实时更新功能对于许多应用程序(如聊天应用、协作工具和在线游戏)都是必不可少的。虽然 WebSocket 是一种常用的实时通信技术,但 Google 的 Firestore 也提供了一种强大的替代方案,使得实时监听变得…