[英]Is there a way to save TQDM console output to a file?
你可以使用這樣的東西。
import tqdm
import time
fh = open('demo.txt','a')
inital_pos = fh.tell()
# This will run for a minute
for t in trange(120):
fh.seek(inital_pos)
time.sleep(0.5)
fh.close()
當使用控制台時,這與\r
的行為類似,因為它會在每個循環中重置文件的末尾,從而避免每次更新時都在新行中打印進度條。
如果我將sys.stderr
重定向到文件,那么我會在文件中得到tqdm
。
import tqdm
import time
import sys
fh = open('output.txt', 'w') # one file for both `stdout` and `stderr`
original_stderr = sys.stderr
sys.stderr = fh
#original_stdout = sys.stdout
#sys.stdout = fh
items = 100
for i in tqdm.tqdm(range(items)):
time.sleep(0.1)
sys.stderr = original_stderr
#sys.stdout = original_stdout
fh.close()
或者我可以使用tqdm(..., file=fh)
import tqdm
import time
fh = open('output.txt', 'w')
items = 100
for i in tqdm.tqdm(range(items), file=fh):
time.sleep(0.1)
fh.close()
但是這個文件有這樣的東西
0%| | 0/100 [00:00<?, ?it/s]
1%| | 1/100 [00:00<00:09, 9.98it/s]
2%|▏ | 2/100 [00:00<00:09, 9.84it/s]
3%|▎ | 3/100 [00:00<00:09, 9.87it/s]
4%|▍ | 4/100 [00:00<00:09, 9.90it/s]
5%|▌ | 5/100 [00:00<00:09, 9.92it/s]
6%|▌ | 6/100 [00:00<00:09, 9.93it/s]
7%|▋ | 7/100 [00:00<00:09, 9.93it/s]
8%|▊ | 8/100 [00:00<00:09, 9.94it/s]
9%|▉ | 9/100 [00:00<00:09, 9.94it/s]
10%|█ | 10/100 [00:01<00:09, 9.94it/s]
11%|█ | 11/100 [00:01<00:08, 9.94it/s]
12%|█▏ | 12/100 [00:01<00:08, 9.94it/s]
13%|█▎ | 13/100 [00:01<00:08, 9.95it/s]
14%|█▍ | 14/100 [00:01<00:08, 9.95it/s]
15%|█▌ | 15/100 [00:01<00:08, 9.95it/s]
16%|█▌ | 16/100 [00:01<00:08, 9.94it/s]
17%|█▋ | 17/100 [00:01<00:08, 9.95it/s]
18%|█▊ | 18/100 [00:01<00:08, 9.95it/s]
19%|█▉ | 19/100 [00:01<00:08, 9.95it/s]
20%|██ | 20/100 [00:02<00:08, 9.95it/s]
21%|██ | 21/100 [00:02<00:07, 9.95it/s]
tqdm
使用 char \\r
移動到行首並打印新文本。
我在 Linux 上的編輯器將其顯示為新行,但在 Windows 上,您可能會在一行中看到它,例如
0%| | 0/100 [00:00<?, ?it/s]\r 1%| | 1/100 [00:00<00:09, 9.98it/s]\r 2%|▏ | 2/100 [00:00<00:09, 9.84it/s]
如果你想獲得最終的價值it/s
那么你寧願使用time.time()
並手動計算它。
import tqdm
import time
import sys
items = 100
start = time.time()
for i in tqdm.tqdm(range(items)):
time.sleep(0.1)
end = time.time()
diff = end-start
items_per_second = items/diff
print(f'time: {diff:.2f} s | {items_per_second:.2f} it/s')
結果:
time: 10.09 s | 9.91 it/s
當您在控制台/終端中運行代碼時print(..., file=fh)
您可以使用fh.write()
或print(..., file=fh)
或重定向sys.stdout
或重定向來寫入文件
python script.py > output.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.