tqdm
มาจากคำภาษาอาหรับ taqaddum (تقدّم) ซึ่งอาจหมายถึง "ความก้าวหน้า" และเป็นคำย่อของ "ฉันรักคุณมาก" ในภาษาสเปน ( te quiero demasiado )
ทำให้ลูปของคุณแสดงมาตรวัดความคืบหน้าอัจฉริยะทันที - เพียงห่อ iterable ใดๆ ด้วย tqdm(iterable)
เท่านี้ก็เสร็จเรียบร้อย!
from tqdm import tqdm
for i in tqdm ( range ( 10000 )):
...
76%|████████████████████████ | 7568/10000 [00:33<00:10, 229.00it/s]
trange(N)
ยังสามารถใช้เป็นทางลัดที่สะดวกสำหรับ tqdm(range(N))
นอกจากนี้ยังสามารถดำเนินการเป็นโมดูลที่มีไปป์ได้:
$ seq 9999999 | tqdm --bytes | wc -l
75.2MB [00:00, 217MB/s]
9999999
$ tar -zcf - docs/ | tqdm --bytes --total ` du -sb docs/ | cut -f1 `
> backup.tgz
32% | ██████████▍ | 8.89G/27.9G [00: 42< 01:31, 223MB/s]
โอเวอร์เฮดต่ำ - ประมาณ 60ns ต่อการวนซ้ำ (80ns พร้อม tqdm.gui
) และมีการทดสอบหน่วยเทียบกับการถดถอยของประสิทธิภาพ จากการเปรียบเทียบ ProgressBar ที่มีชื่อเสียงมีโอเวอร์เฮด 800ns/iter
นอกจากค่าใช้จ่ายที่ต่ำแล้ว tqdm
ยังใช้อัลกอริธึมอัจฉริยะเพื่อคาดการณ์เวลาที่เหลืออยู่ และข้ามการแสดงการวนซ้ำที่ไม่จำเป็น ซึ่งช่วยให้มีค่าใช้จ่ายเพียงเล็กน้อยในกรณีส่วนใหญ่
tqdm
ทำงานบนทุกแพลตฟอร์ม (Linux, Windows, Mac, FreeBSD, NetBSD, Solaris/SunOS) ในคอนโซลใดๆ หรือใน GUI และยังเป็นมิตรกับโน้ตบุ๊ก IPython/Jupyter
tqdm
ไม่ต้องการการพึ่งพาใด ๆ (ไม่ใช่แม้แต่ curses
!) เพียง Python และสภาพแวดล้อมที่รองรับอักขระควบคุม carriage return r
และ line feed n
สารบัญ
contrib
asyncio
logging
pip install tqdm
ดึงและติดตั้งสาขา devel
ก่อนวางจำหน่าย:
pip install " git+https://github.com/tqdm/tqdm.git@devel#egg=tqdm "
conda install -c conda-forge tqdm
มีให้เลือก 3 ช่องทาง คือ
snap install tqdm # implies --stable, i.e. latest tagged release
snap install tqdm --candidate # master branch
snap install tqdm --edge # devel branch
โปรดทราบว่าไบนารี snap
นั้นมีไว้สำหรับการใช้งาน CLI เท่านั้น (ไม่สามารถ import
) และตั้งค่าการเติมแท็บ bash
ให้สมบูรณ์โดยอัตโนมัติ
docker pull tqdm/tqdm
docker run -i --rm tqdm/tqdm --help
มีที่อื่นๆ (ไม่เป็นทางการ) ที่สามารถดาวน์โหลด tqdm
ได้ โดยเฉพาะสำหรับการใช้งาน CLI:
รายการการเปลี่ยนแปลงทั้งหมดมีอยู่ทั้งในรุ่นของ GitHub: บนวิกิ หรือบนเว็บไซต์
tqdm
มีความหลากหลายมากและสามารถใช้ได้หลายวิธี ทั้งสามหลักได้รับด้านล่าง
ล้อม tqdm()
รอบ ๆ ที่สามารถทำซ้ำได้:
from tqdm import tqdm
from time import sleep
text = ""
for char in tqdm ([ "a" , "b" , "c" , "d" ]):
sleep ( 0.25 )
text = text + char
trange(i)
เป็นอินสแตนซ์ที่ได้รับการปรับปรุงเป็นพิเศษของ tqdm(range(i))
:
from tqdm import trange
for i in trange ( 100 ):
sleep ( 0.01 )
การสร้างอินสแตนซ์นอกลูปช่วยให้สามารถควบคุม tqdm()
:
pbar = tqdm ([ "a" , "b" , "c" , "d" ])
for char in pbar :
sleep ( 0.25 )
pbar . set_description ( "Processing %s" % char )
การควบคุมการอัพเดต tqdm()
ด้วยตนเองโดยใช้คำสั่ง with
:
with tqdm ( total = 100 ) as pbar :
for i in range ( 10 ):
sleep ( 0.1 )
pbar . update ( 10 )
หากมีการระบุตัวแปรทางเลือก total
(หรือสามารถวนซ้ำได้ด้วย len()
) สถิติการทำนายจะปรากฏขึ้น
with
เป็นทางเลือกด้วย (คุณสามารถกำหนด tqdm()
ให้กับตัวแปรได้ แต่ในกรณีนี้อย่าลืม del
หรือ close()
ต่อท้าย:
pbar = tqdm ( total = 100 )
for i in range ( 10 ):
sleep ( 0.1 )
pbar . update ( 10 )
pbar . close ()
บางทีการใช้ tqdm
ที่ยอดเยี่ยมที่สุดอาจอยู่ในสคริปต์หรือบนบรรทัดคำสั่ง เพียงแทรก tqdm
(หรือ python -m tqdm
) ระหว่างไพพ์จะส่งผ่าน stdin
ทั้งหมดไปยัง stdout
ในขณะที่พิมพ์ความคืบหน้าไปยัง stderr
ตัวอย่างด้านล่างสาธิตการนับจำนวนบรรทัดในไฟล์ Python ทั้งหมดในไดเร็กทอรีปัจจุบัน พร้อมข้อมูลเวลารวมอยู่ด้วย
$ time find . -name ' *.py ' -type f -exec cat { } ; | wc -l
857365
real 0m3.458s
user 0m0.274s
sys 0m3.325s
$ time find . -name ' *.py ' -type f -exec cat { } ; | tqdm | wc -l
857366it [00:03, 246471.31it/s]
857365
real 0m3.585s
user 0m0.862s
sys 0m3.358s
โปรดทราบว่าสามารถระบุอาร์กิวเมนต์ปกติสำหรับ tqdm
ได้เช่นกัน
$ find . -name ' *.py ' -type f -exec cat { } ; |
tqdm --unit loc --unit_scale --total 857366 >> /dev/null
100% | █████████████████████████████████ | 857K/857K [00: 04< 00:00, 246Kloc/s]
กำลังสำรองไดเร็กทอรีขนาดใหญ่หรือไม่?
$ tar -zcf - docs/ | tqdm --bytes --total ` du -sb docs/ | cut -f1 `
> backup.tgz
44% | ██████████████▊ | 153M/352M [00: 14< 00:18, 11.0MB/s]
สิ่งนี้สามารถตกแต่งให้สวยงามยิ่งขึ้น:
$ BYTES= $( du -sb docs/ | cut -f1 )
$ tar -cf - docs/
| tqdm --bytes --total " $BYTES " --desc Processing | gzip
| tqdm --bytes --total " $BYTES " --desc Compressed --position 1
> ~ /backup.tgz
Processing: 100% | ██████████████████████ | 352M/352M [00: 14< 00:00, 30.2MB/s]
Compressed: 42% | █████████▎ | 148M/352M [00: 14< 00:19, 10.9MB/s]
หรือทำในระดับไฟล์โดยใช้ 7-zip:
$ 7z a -bd -r backup.7z docs/ | grep Compressing
| tqdm --total $( find docs/ -type f | wc -l ) --unit files
| grep -v Compressing
100% | ██████████████████████████▉ | 15327/15327 [01: 00< 00:00, 712.96files/s]
โปรแกรม CLI ที่มีอยู่แล้วซึ่งแสดงผลข้อมูลความคืบหน้าพื้นฐานอยู่แล้วจะได้รับประโยชน์จากแฟล็ก --update
และ --update_to
ของ tqdm
:
$ seq 3 0.1 5 | tqdm --total 5 --update_to --null
100% | ████████████████████████████████████ | 5.0/5 [00: 00< 00:00, 9673.21it/s]
$ seq 10 | tqdm --update --null # 1 + 2 + ... + 10 = 55 iterations
55it [00:00, 90006.52it/s]
ปัญหาที่พบบ่อยที่สุดเกี่ยวข้องกับเอาต์พุตที่มากเกินไปในหลายบรรทัด แทนที่จะเป็นแถบความคืบหน้าบรรทัดเดียวที่ดูเรียบร้อย
CR
, r
)r
อย่างถูกต้อง (cloudwatch, K8s) อาจได้รับประโยชน์จาก export TQDM_POSITION=-1
colorama
ของโมดูล Python เพื่อให้แน่ใจว่าแถบที่ซ้อนกันจะอยู่ภายในบรรทัดที่เกี่ยวข้องascii
เท่านั้นtqdm
ไม่ได้tqdm(enumerate(...))
ด้วย enumerate(tqdm(...))
หรือ tqdm(enumerate(x), total=len(x), ...)
เช่นเดียวกับ numpy.ndenumerate
tqdm(zip(a, b))
ด้วย zip(tqdm(a), b)
หรือแม้แต่ zip(tqdm(a), tqdm(b))
itertools
tqdm.contrib
docker-compose run
แทน docker-compose up
และ tty: true
export TQDM_MININTERVAL=5
เพื่อหลีกเลี่ยงสแปมบันทึก ตรรกะการแทนที่นี้ได้รับการจัดการโดยมัณฑนากร tqdm.utils.envwrap
(มีประโยชน์โดยไม่ขึ้นอยู่กับ tqdm
)หากคุณประสบปัญหาอื่นๆ ให้เรียกดูและไฟล์ .
(ตั้งแต่วันที่ 19 พฤษภาคม 2559)
class tqdm ():
"""
Decorate an iterable object, returning an iterator which acts exactly
like the original iterable, but prints a dynamically updating
progressbar every time a value is requested.
"""
@ envwrap ( "TQDM_" ) # override defaults via env vars
def __init__ ( self , iterable = None , desc = None , total = None , leave = True ,
file = None , ncols = None , mininterval = 0.1 ,
maxinterval = 10.0 , miniters = None , ascii = None , disable = False ,
unit = 'it' , unit_scale = False , dynamic_ncols = False ,
smoothing = 0.3 , bar_format = None , initial = 0 , position = None ,
postfix = None , unit_divisor = 1000 , write_bytes = False ,
lock_args = None , nrows = None , colour = None , delay = 0 ):
ทำซ้ำได้เพื่อตกแต่งด้วยแถบความคืบหน้า เว้นว่างไว้เพื่อจัดการการอัปเดตด้วยตนเอง
คำนำหน้าสำหรับแถบความคืบหน้า
จำนวนการทำซ้ำที่คาดไว้ หากไม่ระบุ จะใช้ len(iterable) หากเป็นไปได้ หาก float("inf") หรือเป็นทางเลือกสุดท้าย ระบบจะแสดงเฉพาะสถิติความคืบหน้าขั้นพื้นฐานเท่านั้น (ไม่มีการทางพิเศษแห่งประเทศไทย ไม่มีแถบความคืบหน้า) หาก gui
เป็น True และพารามิเตอร์นี้จำเป็นต้องอัปเดตในภายหลัง ให้ระบุจำนวนบวกจำนวนมากเริ่มต้นตามต้องการ เช่น 9e9
หาก [ค่าเริ่มต้น: จริง] จะเก็บร่องรอยของแถบความคืบหน้าทั้งหมดไว้เมื่อสิ้นสุดการวนซ้ำ ถ้า None
จะออกเฉพาะในกรณีที่ position
เป็น 0
io.TextIOWrapper
หรือ io.StringIO
เป็นทางเลือก ระบุตำแหน่งที่จะส่งออกข้อความความคืบหน้า (ค่าเริ่มต้น: sys.stderr) ใช้ file.write(str)
และ file.flush()
วิธีการ สำหรับการเข้ารหัส โปรดดูที่ write_bytes
ความกว้างของข้อความเอาต์พุตทั้งหมด หากระบุไว้ จะปรับขนาดแถบความคืบหน้าแบบไดนามิกเพื่อให้อยู่ภายในขอบเขตนี้ หากไม่ได้ระบุ จะพยายามใช้ความกว้างของสภาพแวดล้อม ทางเลือกคือความกว้าง 10 เมตร และไม่มีขีดจำกัดสำหรับตัวนับและสถิติ ถ้าเป็น 0 จะไม่พิมพ์มิเตอร์ใดๆ (สถิติเท่านั้น)
ช่วงเวลาการอัปเดตการแสดงความคืบหน้าขั้นต่ำ [ค่าเริ่มต้น: 0.1] วินาที
ช่วงเวลาการอัปเดตการแสดงความคืบหน้าสูงสุด [ค่าเริ่มต้น: 10] วินาที ปรับ miniters
โดยอัตโนมัติเพื่อให้สอดคล้องกับ mininterval
หลังจากความล่าช้าในการอัปเดตการแสดงผลเป็นเวลานาน ใช้งานได้เฉพาะเมื่อเปิดใช้งาน dynamic_miniters
หรือเธรดมอนิเตอร์
ช่วงเวลาการอัปเดตแสดงความคืบหน้าขั้นต่ำในการวนซ้ำ หากเป็น 0 และ dynamic_miniters
จะปรับเป็น mininterval
ที่เท่ากันโดยอัตโนมัติ (ประสิทธิภาพของ CPU มากกว่า ดีสำหรับการวนซ้ำแบบแน่น) ถ้า > 0 จะข้ามการแสดงจำนวนการวนซ้ำที่ระบุ ปรับแต่งสิ่งนี้และ mininterval
เพื่อให้ได้ลูปที่มีประสิทธิภาพมาก หากความคืบหน้าของคุณไม่แน่นอนทั้งการวนซ้ำแบบเร็วและช้า (เครือข่าย การข้ามรายการ ฯลฯ) คุณควรตั้งค่า miniters=1
หากไม่ได้ระบุหรือเป็นเท็จ ให้ใช้ยูนิโค้ด (บล็อกเรียบ) เพื่อเติมมิเตอร์ ทางเลือกคือการใช้อักขระ ASCII " 123456789#"
ว่าจะปิดการใช้งาน wrapper แถบความคืบหน้าทั้งหมดหรือไม่ [ค่าเริ่มต้น: เท็จ] หากตั้งค่าเป็นไม่มี ให้ปิดใช้งานเมื่อไม่ใช่ TTY
สตริงที่จะใช้เพื่อกำหนดหน่วยของการวนซ้ำแต่ละครั้ง [ค่าเริ่มต้น: it]
หากเป็น 1 หรือ True จำนวนการวนซ้ำจะลดลง/ปรับขนาดโดยอัตโนมัติ และคำนำหน้าหน่วยเมตริกตามมาตรฐานระบบหน่วยสากลจะถูกเพิ่ม (กิโล เมกะ ฯลฯ) [ค่าเริ่มต้น: เท็จ] หากมีตัวเลขที่ไม่ใช่ศูนย์อื่นๆ จะปรับขนาด total
และ n
หากตั้งค่าไว้ ให้เปลี่ยน ncols
และ nrows
ให้กับสภาพแวดล้อมอย่างต่อเนื่อง (อนุญาตให้ปรับขนาดหน้าต่าง) [ค่าเริ่มต้น: False]
ปัจจัยการปรับให้เรียบของค่าเฉลี่ยเคลื่อนที่แบบเอ็กซ์โพเนนเชียลสำหรับการประมาณความเร็ว (ละเว้นในโหมด GUI) ช่วงตั้งแต่ 0 (ความเร็วเฉลี่ย) ถึง 1 (ความเร็วปัจจุบัน/ทันที) [ค่าเริ่มต้น: 0.3]
ระบุการจัดรูปแบบสตริงแถบแบบกำหนดเอง อาจส่งผลกระทบต่อประสิทธิภาพการทำงาน [ค่าเริ่มต้น: '{l_bar}{bar}{r_bar}'] โดยที่ l_bar='{desc}: {percentage:3.0f}%|' และ r_bar='| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, ' '{rate_fmt}{postfix}]' ตัวแปรที่เป็นไปได้: l_bar, bar, r_bar, n, n_fmt, ผลรวม, Total_fmt, เปอร์เซ็นต์, ที่ผ่านไป, elapsed_s, ncols , nrows, เรียงลำดับ, หน่วย, อัตรา, rate_fmt, rate_noinv, Rate_noinv_fmt, Rate_inv, Rate_inv_fmt, postfix, unit_divisor, เหลืออยู่, เหลืออยู่_s, การทางพิเศษแห่งประเทศไทย โปรดทราบว่าส่วนต่อท้าย `: " จะถูกลบออกโดยอัตโนมัติหลังจาก {desc} หากส่วนหลังว่างเปล่า
ค่าตัวนับเริ่มต้น มีประโยชน์เมื่อรีสตาร์ทแถบความคืบหน้า [ค่าเริ่มต้น: 0] หากใช้ float ให้พิจารณาระบุ {n:.3f}
หรือที่คล้ายกันใน bar_format
หรือระบุ unit_scale
ระบุออฟเซ็ตบรรทัดที่จะพิมพ์แถบนี้ (เริ่มจาก 0) อัตโนมัติ หากไม่ได้ระบุ มีประโยชน์ในการจัดการหลายแท่งพร้อมกัน (เช่น จากเธรด)
*
ไม่จำเป็น ระบุสถิติเพิ่มเติมที่จะแสดงที่ส่วนท้ายของแถบ โทร set_postfix(**postfix)
ถ้าเป็นไปได้ (dict)
[ค่าเริ่มต้น: 1,000] จะถูกละเว้น เว้นแต่ unit_scale
จะเป็น True
ไม่ว่าจะเขียนไบต์ ถ้า (ค่าเริ่มต้น: False) จะเขียน Unicode
ส่งผ่านเพื่อ refresh
สำหรับเอาต์พุตระดับกลาง (การเริ่มต้น การวนซ้ำ และการอัปเดต)
ความสูงของหน้าจอ หากระบุไว้ จะซ่อนแถบที่ซ้อนกันอยู่นอกขอบเขตนี้ หากไม่ระบุ ให้พยายามใช้ความสูงของสภาพแวดล้อม ทางเลือกสำรองคือ 20
สีแท่ง (เช่น 'สีเขียว', '#00ff00')
อย่าแสดงจนกว่า [ค่าเริ่มต้น: 0] วินาทีจะผ่านไป
delim
delim
และค่าเริ่มต้น unit_scale
เป็น True, unit_divisor
เป็น 1,024 และ unit
เป็น 'B'stdin
ไปยังทั้ง stderr
และ stdout
update()
โปรดทราบว่าการดำเนินการนี้ช้า (~2e5 it/s) เนื่องจากทุกอินพุตจะต้องถอดรหัสเป็นตัวเลขself.n
โปรดทราบว่าการดำเนินการนี้ช้า (~2e5 it/s) เนื่องจากทุกอินพุตจะต้องถอดรหัสเป็นตัวเลข class tqdm ():
def update ( self , n = 1 ):
"""
Manually update the progress bar, useful for streams
such as reading files.
E.g.:
>>> t = tqdm(total=filesize) # Initialise
>>> for current_buffer in stream:
... ...
... t.update(len(current_buffer))
>>> t.close()
The last line is highly recommended, but possibly not necessary if
``t.update()`` will be called in such a way that ``filesize`` will be
exactly reached and printed.
Parameters
----------
n : int or float, optional
Increment to add to the internal counter of iterations
[default: 1]. If using float, consider specifying ``{n:.3f}``
or similar in ``bar_format``, or specifying ``unit_scale``.
Returns
-------
out : bool or None
True if a ``display()`` was triggered.
"""
def close ( self ):
"""Cleanup and (if leave=False) close the progressbar."""
def clear ( self , nomove = False ):
"""Clear current bar display."""
def refresh ( self ):
"""
Force refresh the display of this bar.
Parameters
----------
nolock : bool, optional
If ``True``, does not lock.
If [default: ``False``]: calls ``acquire()`` on internal lock.
lock_args : tuple, optional
Passed to internal lock's ``acquire()``.
If specified, will only ``display()`` if ``acquire()`` returns ``True``.
"""
def unpause ( self ):
"""Restart tqdm timer from last print time."""
def reset ( self , total = None ):
"""
Resets to 0 iterations for repeated use.
Consider combining with ``leave=True``.
Parameters
----------
total : int or float, optional. Total to use for the new bar.
"""
def set_description ( self , desc = None , refresh = True ):
"""
Set/modify description of the progress bar.
Parameters
----------
desc : str, optional
refresh : bool, optional
Forces refresh [default: True].
"""
def set_postfix ( self , ordered_dict = None , refresh = True , ** tqdm_kwargs ):
"""
Set/modify postfix (additional stats)
with automatic formatting based on datatype.
Parameters
----------
ordered_dict : dict or OrderedDict, optional
refresh : bool, optional
Forces refresh [default: True].
kwargs : dict, optional
"""
@ classmethod
def write ( cls , s , file = sys . stdout , end = " n " ):
"""Print a message via tqdm (without overlap with bars)."""
@ property
def format_dict ( self ):
"""Public API for read-only member access."""
def display ( self , msg = None , pos = None ):
"""
Use ``self.sp`` to display ``msg`` in the specified ``pos``.
Consider overloading this function when inheriting to use e.g.:
``self.some_frontend(**self.format_dict)`` instead of ``self.sp``.
Parameters
----------
msg : str, optional. What to display (default: ``repr(self)``).
pos : int, optional. Position to ``moveto``
(default: ``abs(self.pos)``).
"""
@ classmethod
@ contextmanager
def wrapattr ( cls , stream , method , total = None , bytes = True , ** tqdm_kwargs ):
"""
stream : file-like object.
method : str, "read" or "write". The result of ``read()`` and
the first argument of ``write()`` should have a ``len()``.
>>> with tqdm.wrapattr(file_obj, "read", total=file_obj.size) as fobj:
... while True:
... chunk = fobj.read(chunk_size)
... if not chunk:
... break
"""
@ classmethod
def pandas ( cls , * targs , ** tqdm_kwargs ):
"""Registers the current `tqdm` class with `pandas`."""
def trange ( * args , ** tqdm_kwargs ):
"""Shortcut for `tqdm(range(*args), **tqdm_kwargs)`."""
def tqdm . contrib . tenumerate ( iterable , start = 0 , total = None ,
tqdm_class = tqdm . auto . tqdm , ** tqdm_kwargs ):
"""Equivalent of `numpy.ndenumerate` or builtin `enumerate`."""
def tqdm . contrib . tzip ( iter1 , * iter2plus , ** tqdm_kwargs ):
"""Equivalent of builtin `zip`."""
def tqdm . contrib . tmap ( function , * sequences , ** tqdm_kwargs ):
"""Equivalent of builtin `map`."""
class tqdm . notebook . tqdm ( tqdm . tqdm ):
"""IPython/Jupyter Notebook widget."""
class tqdm . auto . tqdm ( tqdm . tqdm ):
"""Automatically chooses beween `tqdm.notebook` and `tqdm.tqdm`."""
class tqdm . asyncio . tqdm ( tqdm . tqdm ):
"""Asynchronous version."""
@ classmethod
def as_completed ( cls , fs , * , loop = None , timeout = None , total = None ,
** tqdm_kwargs ):
"""Wrapper for `asyncio.as_completed`."""
class tqdm . gui . tqdm ( tqdm . tqdm ):
"""Matplotlib GUI version."""
class tqdm . tk . tqdm ( tqdm . tqdm ):
"""Tkinter GUI version."""
class tqdm . rich . tqdm ( tqdm . tqdm ):
"""`rich.progress` version."""
class tqdm . keras . TqdmCallback ( keras . callbacks . Callback ):
"""Keras callback for epoch and batch progress."""
class tqdm . dask . TqdmCallback ( dask . callbacks . Callback ):
"""Dask callback for task progress."""
contrib
แพ็คเกจ tqdm.contrib
ยังมีโมดูลทดลองด้วย:
tqdm.contrib.itertools
: แผ่นบางๆ รอบ itertools
tqdm.contrib.concurrent
: เสื้อคลุมบางๆ รอบ concurrent.futures
tqdm.contrib.slack
: โพสต์ไปยังบอท Slacktqdm.contrib.discord
: โพสต์ไปยังบอท Discordtqdm.contrib.telegram
: โพสต์ไปยังบอท Telegramtqdm.contrib.bells
: เปิดใช้งานคุณสมบัติเสริมทั้งหมดโดยอัตโนมัติauto
, pandas
, slack
, discord
, telegram
help()
; ข้อมูลที่กำหนดเองสามารถแสดงและอัพเดตแบบไดนามิกบนแถบ tqdm
พร้อมด้วยอาร์กิวเมนต์ desc
และ postfix
:
from tqdm import tqdm , trange
from random import random , randint
from time import sleep
with trange ( 10 ) as t :
for i in t :
# Description will be displayed on the left
t . set_description ( 'GEN %i' % i )
# Postfix will be displayed on the right,
# formatted automatically based on argument's datatype
t . set_postfix ( loss = random (), gen = randint ( 1 , 999 ), str = 'h' ,
lst = [ 1 , 2 ])
sleep ( 0.1 )
with tqdm ( total = 10 , bar_format = "{postfix[0]} {postfix[1][value]:>8.2g}" ,
postfix = [ "Batch" , { "value" : 0 }]) as t :
for i in range ( 10 ):
sleep ( 0.1 )
t . postfix [ 1 ][ "value" ] = i / 2
t . update ()
ข้อควรจำเมื่อใช้ {postfix[...]}
ในสตริง bar_format
:
postfix
จะต้องส่งผ่านเป็นอาร์กิวเมนต์เริ่มต้นในรูปแบบที่เข้ากันได้ด้วย และpostfix
จะถูกแปลงเป็นสตริงโดยอัตโนมัติหากเป็นวัตถุที่มีลักษณะคล้าย dict
เพื่อป้องกันพฤติกรรมนี้ ให้แทรกรายการพิเศษลงในพจนานุกรมโดยที่คีย์ไม่ใช่สตริง พารามิเตอร์ bar_format
เพิ่มเติมอาจถูกกำหนดโดยการแทนที่ format_dict
และแถบนั้นอาจถูกแก้ไขโดยใช้ ascii
:
from tqdm import tqdm
class TqdmExtraFormat ( tqdm ):
"""Provides a `total_time` format parameter"""
@ property
def format_dict ( self ):
d = super (). format_dict
total_time = d [ "elapsed" ] * ( d [ "total" ] or 0 ) / max ( d [ "n" ], 1 )
d . update ( total_time = self . format_interval ( total_time ) + " in total" )
return d
for i in TqdmExtraFormat (
range (