Python 진행 표시줄
스크립트가 시간이 걸릴 것 같은 작업을 수행할 때 진행 표시줄을 사용하려면 어떻게 해야 합니까?
입니다.True아아아아아아아아아아아아아아아아아아아아.기능이 실행되는 동안 진행 표시줄을 표시하려면 어떻게 해야 합니까?
실시간으로 해야 하기 때문에 어떻게 해야 할지 모르겠어요.thread이 ii ?요.는는모모모모모모
현재 기능 실행 중에는 아무것도 인쇄하지 않지만 진행 표시줄이 좋을 것 같습니다.또, 코드의 관점에서 어떻게 하면 좋은지, 라고 하는 것에 흥미가 있습니다.
tqdm 사용 시 (conda install tqdm ★★★★★★★★★★★★★★★★★」pip install tqdm) 만에 할 수
from time import sleep
from tqdm import tqdm
for i in tqdm(range(10)):
sleep(3)
60%|██████ | 6/10 [00:18<00:12, 0.33 it/s]
또한 노트북 버전도 있습니다.
from tqdm.notebook import tqdm
for i in tqdm(range(100)):
sleep(3)
하시면 됩니다.tqdm.autotqdm.notebook단말기와 노트북 모두에서 작업할 수 있습니다.
tqdm.contrib 에는 다음과 같은 작업을 수행하는 도우미 기능이 포함되어 있습니다.enumerate,map , , , , 입니다.zip에는 동시 맵이 있습니다.
또는 를 사용하여 주피터 노트북에서 연결을 끊은 후 휴대폰으로 진행 상황을 전송할 수도 있습니다.

다음과 같은 특정 라이브러리가 있지만(여기에서는 이와 같이) 매우 간단한 기능을 사용할 수 있습니다.
import time
import sys
toolbar_width = 40
# setup toolbar
sys.stdout.write("[%s]" % (" " * toolbar_width))
sys.stdout.flush()
sys.stdout.write("\b" * (toolbar_width+1)) # return to start of line, after '['
for i in xrange(toolbar_width):
time.sleep(0.1) # do real work here
# update the bar
sys.stdout.write("-")
sys.stdout.flush()
sys.stdout.write("]\n") # this ends the progress bar
주의: 프로그레스바2는 수년간 유지되지 않은 프로그레스바의 포크입니다.
살아있는 프로그레스, 가장 멋진 프로그레스 바를 사용하세요!

진척바 프레임워크를 유용하게 사용하기 위해서는 (완료율과 도착 예정시간(ETA)을 취득하기 위해) 처리의 몇 단계를 수행할지 알 수 있어야 합니다.
그냥 요.yield아이템 마킹이 완료되었으므로 바로 사용하실 수 있습니다!
def compute():
for i in range(1000):
... # process items as usual.
yield # insert this :)
그 후 다음과 같이 사용합니다.
from alive_progress import alive_bar
with alive_bar(1000) as bar:
for i in compute():
bar()
멋지고 생생한 프로그레스 바를 얻으려면!
|█████████████▎ | ▅▃▁ 321/1000 [32%] in 8s (40.1/s, eta: 16s)
공개:나는 의 작가이다.alive-progress하지만 그것은 당신의 문제를 잘 해결해 줄 것이다!상세한 것에 대하여는, https://github.com/rsalmei/alive-progress 의 메뉴얼을 참조해 주세요.이제 Jupyter 노트북에서도 사용할 수 있게 되었습니다!다음은 이 기능을 수행하는 몇 가지 예입니다.


외부 패키지는 없습니다.이미 만들어진 코드 조각.
막대 진행률 기호를 사용자 정의할 수 있습니다."#" , »size, 표시prefixsyslog.
Python 3.3+
import sys
def progressbar(it, prefix="", size=60, out=sys.stdout): # Python3.3+
count = len(it)
def show(j):
x = int(size*j/count)
print("{}[{}{}] {}/{}".format(prefix, "#"*x, "."*(size-x), j, count),
end='\r', file=out, flush=True)
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
print("\n", flush=True, file=out)
사용방법:
import time
for i in progressbar(range(15), "Computing: ", 40):
time.sleep(0.1) # any code you need
, 유니코드를 합니다.u"█" 치환 " " ""#"★★★★★★★★★★★★★★★★for i in progressbar(range(100)): ...다음과 같이 됩니다.
두 번째 스레드는 필요 없습니다.상기의 솔루션/패키지에는, 필요한 것이 있습니다.
모든 반복 가능성과 함께 작동한다는 것은
len()사용할 수 있습니다. a.list,a ,adict를 어떤['a', 'b', 'c' ... 'g']생성기에서는 목록()으로 줄 바꿈만 하면 됩니다.예를들면
for i in progressbar(list(your_generator), "Computing: ", 40):발전기에서 작업이 끝나지 않는 한. 이 경우 tqdm과 같은 다른 솔루션이 필요합니다.
, 도 할 수 있어요.」라고 하는 변경을 할 수 .out로로 합니다.sys.stderr예를들면.
Python 3.6+ (f-string)
def progressbar(it, prefix="", size=60, out=sys.stdout): # Python3.6+
count = len(it)
def show(j):
x = int(size*j/count)
print(f"{prefix}[{u'█'*x}{('.'*(size-x))}] {j}/{count}", end='\r', file=out, flush=True)
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
print("\n", flush=True, file=out)
Python 2(구 코드)
import sys
def progressbar(it, prefix="", size=60, out=sys.stdout):
count = len(it)
def show(j):
x = int(size*j/count)
out.write("%s[%s%s] %i/%i\r" % (prefix, u"#"*x, "."*(size-x), j, count))
out.flush()
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
out.write("\n")
out.flush()
위의 제안들은 매우 좋지만, 대부분의 사람들은 외부 패키지에 의존하지 않고 재사용 가능한 기성 솔루션을 원한다고 생각합니다.
저는 그 중에서 가장 좋은 점을 얻어 테스트 케이스와 함께 함수로 만들었습니다.
사용하려면 "def update_progress(progress)" 아래에 있는 행을 복사하기만 하면 됩니다. 테스트 스크립트는 복사하지 않습니다.sys를 Import하는 것을 잊지 마세요.진행률 표시줄을 표시하거나 업데이트해야 할 때마다 이 명령을 호출합니다.
이 조작은 "\r" 기호를 콘솔에 직접 전송하여 커서를 처음 위치로 되돌리는 방식으로 작동합니다.python의 "인쇄"는 이 목적을 위해 위의 기호를 인식하지 않으므로 "sys"가 필요합니다.
import time, sys
# update_progress() : Displays or updates a console progress bar
## Accepts a float between 0 and 1. Any int will be converted to a float.
## A value under 0 represents a 'halt'.
## A value at 1 or bigger represents 100%
def update_progress(progress):
barLength = 10 # Modify this to change the length of the progress bar
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = "error: progress var must be float\r\n"
if progress < 0:
progress = 0
status = "Halt...\r\n"
if progress >= 1:
progress = 1
status = "Done...\r\n"
block = int(round(barLength*progress))
text = "\rPercent: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), progress*100, status)
sys.stdout.write(text)
sys.stdout.flush()
# update_progress test script
print "progress : 'hello'"
update_progress("hello")
time.sleep(1)
print "progress : 3"
update_progress(3)
time.sleep(1)
print "progress : [23]"
update_progress([23])
time.sleep(1)
print ""
print "progress : -10"
update_progress(-10)
time.sleep(2)
print ""
print "progress : 10"
update_progress(10)
time.sleep(2)
print ""
print "progress : 0->1"
for i in range(101):
time.sleep(0.1)
update_progress(i/100.0)
print ""
print "Test completed"
time.sleep(10)
테스트 스크립트의 결과는 다음과 같습니다(마지막 진행 표시줄이 애니메이션 처리됨).
progress : 'hello'
Percent: [----------] 0% error: progress var must be float
progress : 3
Percent: [##########] 100% Done...
progress : [23]
Percent: [----------] 0% error: progress var must be float
progress : -10
Percent: [----------] 0% Halt...
progress : 10
Percent: [##########] 100% Done...
progress : 0->1
Percent: [##########] 100% Done...
Test completed
https://pypi.python.org/pypi/progress 에서 진행 상황을 시험해 보세요.
from progress.bar import Bar
bar = Bar('Processing', max=20)
for i in range(20):
# Do some work
bar.next()
bar.finish()
결과는 다음과 같은 막대가 됩니다.
Processing |############# | 42/100
유사한 애플리케이션(루프 진행 상황을 추적)을 위해 python-progress bar를 사용했습니다.
그들의 예는 다음과 같습니다.
from progressbar import * # just a simple progress bar
widgets = ['Test: ', Percentage(), ' ', Bar(marker='0',left='[',right=']'),
' ', ETA(), ' ', FileTransferSpeed()] #see docs for other options
pbar = ProgressBar(widgets=widgets, maxval=500)
pbar.start()
for i in range(100,500+1,50):
# here do something long at each iteration
pbar.update(i) #this adds a little symbol at each iteration
pbar.finish()
print
여기서 동등한 솔루션을 검색한 후, 제 요구에 맞는 간단한 진척 클래스를 만들었습니다.게시하는 게 좋을 것 같아서요
from __future__ import print_function
import sys
import re
class ProgressBar(object):
DEFAULT = 'Progress: %(bar)s %(percent)3d%%'
FULL = '%(bar)s %(current)d/%(total)d (%(percent)3d%%) %(remaining)d to go'
def __init__(self, total, width=40, fmt=DEFAULT, symbol='=',
output=sys.stderr):
assert len(symbol) == 1
self.total = total
self.width = width
self.symbol = symbol
self.output = output
self.fmt = re.sub(r'(?P<name>%\(.+?\))d',
r'\g<name>%dd' % len(str(total)), fmt)
self.current = 0
def __call__(self):
percent = self.current / float(self.total)
size = int(self.width * percent)
remaining = self.total - self.current
bar = '[' + self.symbol * size + ' ' * (self.width - size) + ']'
args = {
'total': self.total,
'bar': bar,
'current': self.current,
'percent': percent * 100,
'remaining': remaining
}
print('\r' + self.fmt % args, file=self.output, end='')
def done(self):
self.current = self.total
self()
print('', file=self.output)
예:
from time import sleep
progress = ProgressBar(80, fmt=ProgressBar.FULL)
for x in xrange(progress.total):
progress.current += 1
progress()
sleep(0.1)
progress.done()
다음을 인쇄합니다.
[======== ] 17/80 ( 21%) 63 to go
tqdm 을 사용할 수 있습니다.
from tqdm import tqdm
with tqdm(total=100, desc="Adding Users", bar_format="{l_bar}{bar} [ time left: {remaining} ]") as pbar:
for i in range(100):
time.sleep(3)
pbar.update(1)
이 예에서는 프로그레스바가 5분간 실행되고 있으며 다음과 같이 표시됩니다.
Adding Users: 3%|█████▊ [ time left: 04:51 ]
원하는 대로 변경하고 사용자 지정할 수 있습니다.
Brian Khuu의 답변은 단순하고 외부 패키지가 필요하지 않기 때문에 마음에 듭니다.조금 변경했기 때문에 여기에 버전을 추가합니다.
import sys
import time
def updt(total, progress):
"""
Displays or updates a console progress bar.
Original source: https://stackoverflow.com/a/15860757/1391441
"""
barLength, status = 20, ""
progress = float(progress) / float(total)
if progress >= 1.:
progress, status = 1, "\r\n"
block = int(round(barLength * progress))
text = "\r[{}] {:.0f}% {}".format(
"#" * block + "-" * (barLength - block), round(progress * 100, 0),
status)
sys.stdout.write(text)
sys.stdout.flush()
runs = 300
for run_num in range(runs):
time.sleep(.1)
updt(runs, run_num + 1)
수( 「 」 )를 사용합니다.total입니다.progress를 상정하고 있습니다.total >= progress을 사용하다
[#####---------------] 27%
python-progress bar는 매우 사용하기 쉽기 때문에 매우 마음에 듭니다.
가장 간단한 경우로, 다음과 같습니다.
import progressbar
import time
progress = progressbar.ProgressBar()
for i in progress(range(80)):
time.sleep(0.01)
아피아란스를 커스터마이즈 할 수 있으며, 남은 예상 시간을 표시할 수 있습니다.예를 들어 위와 동일한 코드를 사용합니다.
progress = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ',
progressbar.Percentage(), ' ',
progressbar.ETA()])
라이브러리 사용: (GitHub).
사용방법:
>>> import fish
>>> while churning:
... churn_churn()
... fish.animate()
재미있게 보내!
시간이 많이 걸리는 반복량이 큰 루프라면 제가 만든 이 기능을 사용하셔도 됩니다.루프를 반복할 때마다 진척이 추가됩니다.여기서 count는 루프의 현재 반복입니다.total은 루프할 값이고 size(int)는 막대 크기를 10자 단위로 나타냅니다. (크기 1 = 10자, 크기 2 = 20자)
import sys
def loadingBar(count,total,size):
percent = float(count)/float(total)*100
sys.stdout.write("\r" + str(int(count)).rjust(3,'0')+"/"+str(int(total)).rjust(3,'0') + ' [' + '='*int(percent/10)*size + ' '*(10-int(percent/10))*size + ']')
예:
for i in range(0,100):
loadingBar(i,100,2)
#do some code
출력:
i = 50
>> 050/100 [========== ]
심플한 오네라이너:
K = 628318
for k in range(K):
# your stuff
print(end="\r|%-80s|" % ("="*int(80*k/(K-1))))
|===================================================================== |
80달러 당신은 된다.print().
또한 디지털 진행률 표시기를 잊지 마십시오.
K = 628318
for k in range(K):
# your stuff
print(end="\r%6.2f %%" % (k/(K-1)*100))
94.53 %
필요하다면 이 둘을 결합하는 것은 그리 어렵지 않다.
는 ' 리턴'입니다.\r 「」의 합니다.end="\n"print.
아래 코드는 매우 일반적인 솔루션이며 경과시간과 남은 견적을 가지고 있습니다.당신은 그것과 함께 어떤 반복 가능한 것도 사용할 수 있습니다.진행률 표시줄의 크기는 25자로 고정되어 있지만 전체, 절반 및 1/4 블록 문자를 사용하여 1% 단계로 업데이트를 표시할 수 있습니다.출력은 다음과 같습니다.
18% |████▌ | \ [0:00:01, 0:00:06]
예를 들어 코드:
import sys, time
from numpy import linspace
def ProgressBar(iterObj):
def SecToStr(sec):
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
return u'%d:%02d:%02d'%(h, m, s)
L = len(iterObj)
steps = {int(x):y for x,y in zip(linspace(0, L, min(100,L), endpoint=False),
linspace(0, 100, min(100,L), endpoint=False))}
qSteps = ['', u'\u258E', u'\u258C', u'\u258A'] # quarter and half block chars
startT = time.time()
timeStr = ' [0:00:00, -:--:--]'
activity = [' -',' \\',' |',' /']
for nn,item in enumerate(iterObj):
if nn in steps:
done = u'\u2588'*int(steps[nn]/4.0)+qSteps[int(steps[nn]%4)]
todo = ' '*(25-len(done))
barStr = u'%4d%% |%s%s|'%(steps[nn], done, todo)
if nn>0:
endT = time.time()
timeStr = ' [%s, %s]'%(SecToStr(endT-startT),
SecToStr((endT-startT)*(L/float(nn)-1)))
sys.stdout.write('\r'+barStr+activity[nn%4]+timeStr); sys.stdout.flush()
yield item
barStr = u'%4d%% |%s|'%(100, u'\u2588'*25)
timeStr = ' [%s, 0:00:00]\n'%(SecToStr(time.time()-startT))
sys.stdout.write('\r'+barStr+timeStr); sys.stdout.flush()
# Example
s = ''
for c in ProgressBar(list('Disassemble and reassemble this string')):
time.sleep(0.2)
s += c
print(s)
개선사항이나 기타 의견을 주시면 감사하겠습니다.건배!
Python3에서는 매우 간단합니다.
import time
import math
def show_progress_bar(bar_length, completed, total):
bar_length_unit_value = (total / bar_length)
completed_bar_part = math.ceil(completed / bar_length_unit_value)
progress = "*" * completed_bar_part
remaining = " " * (bar_length - completed_bar_part)
percent_done = "%.2f" % ((completed / total) * 100)
print(f'[{progress}{remaining}] {percent_done}%', end='\r')
bar_length = 30
total = 100
for i in range(0, total + 1):
show_progress_bar(bar_length, i, total)
time.sleep(0.1)
print('\n')
주피터 노트북에서 실행 중일 때 일반 tqdm은 여러 줄에 출력을 쓰기 때문에 작동하지 않습니다.대신 이것을 사용하세요.
import time
from tqdm import tqdm_notebook as tqdm
for i in tqdm(range(100))
time.sleep(0.5)
이 페이지가 마음에 들어요.
간단한 예에서 시작하여 멀티 스레드 버전으로 이동합니다.바로 사용할 수 있습니다.서드파티 패키지는 필요 없습니다.
코드는 다음과 같습니다.
import time
import sys
def do_task():
time.sleep(1)
def example_1(n):
for i in range(n):
do_task()
print '\b.',
sys.stdout.flush()
print ' Done!'
print 'Starting ',
example_1(10)
또는 다음 예제에서는 프로그램 실행 중에 회전 로드 바를 실행하기 위해 스레드를 사용하는 방법을 보여 줍니다.
import sys
import time
import threading
class progress_bar_loading(threading.Thread):
def run(self):
global stop
global kill
print 'Loading.... ',
sys.stdout.flush()
i = 0
while stop != True:
if (i%4) == 0:
sys.stdout.write('\b/')
elif (i%4) == 1:
sys.stdout.write('\b-')
elif (i%4) == 2:
sys.stdout.write('\b\\')
elif (i%4) == 3:
sys.stdout.write('\b|')
sys.stdout.flush()
time.sleep(0.2)
i+=1
if kill == True:
print '\b\b\b\b ABORT!',
else:
print '\b\b done!',
kill = False
stop = False
p = progress_bar_loading()
p.start()
try:
#anything you want to run.
time.sleep(1)
stop = True
except KeyboardInterrupt or EOFError:
kill = True
stop = True
하였습니다.format()★★★★★★★★★★★★★★★★★★★★★★★★★★★저의 솔루션은 다음과 같습니다.
import time
loadbarwidth = 23
for i in range(1, loadbarwidth + 1):
time.sleep(0.1)
strbarwidth = '[{}{}] - {}\r'.format(
(i * '#'),
((loadbarwidth - i) * '-'),
(('{:0.2f}'.format(((i) * (100/loadbarwidth))) + '%'))
)
print(strbarwidth ,end = '')
print()
출력:
[#######################] - 100.00%
다음은 로딩 바를 프로그래밍 방식으로 작성하는 간단한 솔루션입니다(필요한 기간은 사용자가 결정해야 합니다).
import time
n = 33 # or however many loading slots you want to have
load = 0.01 # artificial loading time!
loading = '.' * n # for strings, * is the repeat operator
for i in range(n+1):
# this loop replaces each dot with a hash!
print('\r%s Loading at %3d percent!' % (loading, i*100/n), end='')
loading = loading[:i] + '#' + loading[i+1:]
time.sleep(load)
if i==n: print()
2022 외부 라이브러리 없이 단순 진행 표시줄에 대한 답변
import time, sys
def progress(size):
for item in range(size):
if(item==0):
print("[",end="")
elif(item==size-1):
print("]",end="\n")
else:
#main work goes here
time.sleep(0.1)
print("%",end="")
sys.stdout.flush()
progress(50)
작업을 측정 가능한 덩어리로 분할할 수 없는 경우, 새로운 스레드로 기능을 호출하고 작업 소요 시간을 지정할 수 있습니다.
import thread
import time
import sys
def work():
time.sleep( 5 )
def locked_call( func, lock ):
lock.acquire()
func()
lock.release()
lock = thread.allocate_lock()
thread.start_new_thread( locked_call, ( work, lock, ) )
# This part is icky...
while( not lock.locked() ):
time.sleep( 0.1 )
while( lock.locked() ):
sys.stdout.write( "*" )
sys.stdout.flush()
time.sleep( 1 )
print "\nWork Done"
필요에 따라 타이밍 정밀도를 높일 수 있습니다.
나는 가브리엘의 대답을 좋아하지만, 유연하게 바꾸었습니다.함수에 막대 길이를 보내고 원하는 길이의 진행 표시줄을 가져올 수 있습니다.또한 진행 표시줄의 길이가 0이거나 음수일 수 없습니다.또, Gabriel answer와 같이 사용할 수 있습니다(예 #2를 참조).
import sys
import time
def ProgressBar(Total, Progress, BarLength=20, ProgressIcon="#", BarIcon="-"):
try:
# You can't have a progress bar with zero or negative length.
if BarLength <1:
BarLength = 20
# Use status variable for going to the next line after progress completion.
Status = ""
# Calcuting progress between 0 and 1 for percentage.
Progress = float(Progress) / float(Total)
# Doing this conditions at final progressing.
if Progress >= 1.:
Progress = 1
Status = "\r\n" # Going to the next line
# Calculating how many places should be filled
Block = int(round(BarLength * Progress))
# Show this
Bar = "[{}] {:.0f}% {}".format(ProgressIcon * Block + BarIcon * (BarLength - Block), round(Progress * 100, 0), Status)
return Bar
except:
return "ERROR"
def ShowBar(Bar):
sys.stdout.write(Bar)
sys.stdout.flush()
if __name__ == '__main__':
print("This is a simple progress bar.\n")
# Example #1:
print('Example #1')
Runs = 10
for i in range(Runs + 1):
progressBar = "\rProgress: " + ProgressBar(10, i, Runs)
ShowBar(progressBar)
time.sleep(1)
# Example #2:
print('\nExample #2')
Runs = 10
for i in range(Runs + 1):
progressBar = "\rProgress: " + ProgressBar(10, i, 20, '|', '.')
ShowBar(progressBar)
time.sleep(1)
print('\nDone.')
# Example #2:
Runs = 10
for i in range(Runs + 1):
ProgressBar(10, i)
time.sleep(1)
결과:
이것은 단순한 진행률 바입니다.
예 #1
진행상황 : [##------------------------------------------
예 #2
진척도: [|||||||||........]60 %
다 했어요.
Python 3.6 PEP 498에서 소개된 "f-string"을 사용하기 때문에 조금 늦었지만 현재 버전의 Python 3을 사용하는 사람들에게는 효과가 있을 것입니다.
코드
from numpy import interp
class Progress:
def __init__(self, value, end, title='Downloading',buffer=20):
self.title = title
#when calling in a for loop it doesn't include the last number
self.end = end -1
self.buffer = buffer
self.value = value
self.progress()
def progress(self):
maped = int(interp(self.value, [0, self.end], [0, self.buffer]))
print(f'{self.title}: [{"#"*maped}{"-"*(self.buffer - maped)}]{self.value}/{self.end} {((self.value/self.end)*100):.2f}%', end='\r')
예
#some loop that does perfroms a task
for x in range(21) #set to 21 to include until 20
Progress(x, 21)
산출량
Downloading: [########------------] 8/20 40.00%
진행률 라이브러리를 사용하십시오.
pip install progress
다음은 ETA/Except 시간을 읽기 쉬운 형식으로 포맷하기 위해 작성한 커스텀 서브클래스입니다.
import datetime
from progress.bar import IncrementalBar
class ProgressBar(IncrementalBar):
'''
My custom progress bar that:
- Show %, count, elapsed, eta
- Time is shown in H:M:S format
'''
message = 'Progress'
suffix = '%(percent).1f%% (%(index)d/%(max)d) -- %(elapsed_min)s (eta: %(eta_min)s)'
def formatTime(self, seconds):
return str(datetime.timedelta(seconds=seconds))
@property
def elapsed_min(self):
return self.formatTime(self.elapsed)
@property
def eta_min(self):
return self.formatTime(self.eta)
if __name__=='__main__':
counter = 120
bar = ProgressBar('Processing', max=counter)
for i in range(counter):
bar.next()
time.sleep(1)
bar.finish()
간단한 해결책은 다음과 같습니다.
import time
def progress(_cur, _max):
p = round(100*_cur/_max)
b = f"Progress: {p}% - ["+"."*int(p/5)+" "*(20-int(p/5))+"]"
print(b, end="\r")
# USAGE:
for i in range(0,101):
time.sleep(0.1)
progress(i,100)
print("..."*5, end="\r")
print("Done")
매우 심플한 접근법:
def progbar(count: int) -> None:
for i in range(count):
print(f"[{i*'#'}{(count-1-i)*' '}] - {i+1}/{count}", end="\r")
yield i
print('\n')
사용방법:
from time import sleep
for i in progbar(10):
sleep(0.2) #whatever task you need to do
PyProg를 사용해 보세요.PyProg는 Python용 오픈 소스 라이브러리이며, 커스터마이즈 가능한 슈퍼 프로그레스 인디케이터와 바를 만듭니다.
현재 버전 1.0.2로 Github에서 호스팅되며 PyPI에서 사용할 수 있습니다(아래 링크).Python 3 & 2와 호환되며 Qt Console에서도 사용할 수 있습니다.
정말 사용하기 편해요.다음 코드:
import pyprog
from time import sleep
# Create Object
prog = pyprog.ProgressBar(" ", "", 34)
# Update Progress Bar
prog.update()
for i in range(34):
# Do something
sleep(0.1)
# Set current status
prog.set_stat(i + 1)
# Update Progress Bar again
prog.update()
# Make the Progress Bar final
prog.end()
작성 내용:
Initial State:
Progress: 0% --------------------------------------------------
When half done:
Progress: 50% #########################-------------------------
Final State:
Progress: 100% ##################################################
심플하지만 커스터마이즈 가능한 프로그레스바 라이브러리가 필요했기 때문에 실제로 PyProg를 만들었습니다.다음과 같이 간단하게 설치할 수 있습니다.pip install pyprog.
PyProg Github : https://github.com/Bill13579/pyprog
PyPI: https://pypi.python.org/pypi/pyprog/
계몽을 사용할 수도 있습니다.주요 장점은 진행 표시줄을 덮어쓰지 않고 동시에 로그인할 수 있다는 것입니다.
import time
import enlighten
manager = enlighten.Manager()
pbar = manager.counter(total=100)
for num in range(1, 101):
time.sleep(0.05)
print('Step %d complete' % num)
pbar.update()
또한 여러 진행 표시줄을 처리합니다.
import time
import enlighten
manager = enlighten.Manager()
odds = manager.counter(total=50)
evens = manager.counter(total=50)
for num in range(1, 101):
time.sleep(0.05)
if num % 2:
odds.update()
else:
evens.update()
jelde015의 좀 더 일반적인 대답(물론 그에게 신용)
로딩 바를 수동으로 업데이트하기 위한 방법은 다음과 같습니다.
import sys
from math import *
def loadingBar(i, N, size):
percent = float(i) / float(N)
sys.stdout.write("\r"
+ str(int(i)).rjust(3, '0')
+"/"
+str(int(N)).rjust(3, '0')
+ ' ['
+ '='*ceil(percent*size)
+ ' '*floor((1-percent)*size)
+ ']')
그리고 그것을 호출:
loadingBar(7, 220, 40)
결과는 다음과 같습니다.
007/220 [= ]
시류를 타고 언제든지 부를 수 있어i가치.
을 설정하다size바의 글자 수만큼
언급URL : https://stackoverflow.com/questions/3160699/python-progress-bar
'source' 카테고리의 다른 글
| Mariadb 컨테이너는 3310 대신 포트 3306을 여전히 구속하고 있습니다. (0) | 2023.01.15 |
|---|---|
| 다른 스크립트에서 스크립트를 호출하는 가장 좋은 방법은 무엇입니까? (0) | 2023.01.15 |
| Python 함수에서 두 개의 값을 반환하려면 어떻게 해야 합니까? (0) | 2023.01.15 |
| PHP 목록()과 동등한 Javascript (0) | 2023.01.15 |
| InnoDB는 문자열을 어떻게 저장합니까? (0) | 2023.01.15 |
