帮助解决Python中的while循环行为
我有一个脚本,用简单的循环来显示进度条,但它的表现并没有我预期的那样好:
count = 1
maxrecords = len(international)
p = ProgressBar("Blue")
t = time
while count < maxrecords:
print 'Processing %d of %d' % (count, maxrecords)
percent = float(count) / float(maxrecords) * 100
p.render(int(percent))
t.sleep(0.5)
count += 1
看起来它在“p.render...”那里一直循环,而没有回到“print 'Processing %d of %d...'”。
更新:抱歉,看来ProgressBar.render()在渲染进度条时,会把“print 'Processing...”的输出给覆盖掉。这个进度条来自于http://nadiana.com/animated-terminal-progress-bar-in-python
4 个回答
3
这不是在Python中写循环的正确方式。
maxrecords = len(international)
p = ProgressBar("Blue")
for count in range(1, maxrecords):
print 'Processing %d of %d' % (count, maxrecords)
percent = float(count) / float(maxrecords) * 100
p.render(int(percent))
time.sleep(0.5)
如果你真的想对记录做点什么,而不仅仅是显示条形图,你应该这样做:
maxrecords = len(international)
for count, record in enumerate(international):
print 'Processing %d of %d' % (count, maxrecords)
percent = float(count) / float(maxrecords) * 100
p.render(int(percent))
process_record(record) # or whatever the function is
5
我看到你在我的网站上使用了进度条的实现。如果你想打印一条消息,可以在渲染时使用消息参数。
p.render(percent, message='Processing %d of %d' % (count, maxrecords))
2
ProgressBar.render()
这个函数是怎么实现的?我猜它是在输出一些终端控制字符,这些字符可以移动光标的位置,从而覆盖之前的输出内容。这可能会让人误以为程序的运行流程出现了问题,其实并不是这样。