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.pswp.cn/diannao/43807.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/43807.shtml
英文地址,請注明出處:http://en.pswp.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 也提供了一種強大的替代方案,使得實時監聽變得…