我正在读取文本文件中的行形式,然后每行执行操作.由于文本文件的大小和每个动作的时间500 =>.秒.我希望能够查看进度,但不确定从哪里开始.
这是我正在使用的示例脚本,该如何编写呢?
import os
tmp = "test.txt"
f = open(tmp,'r')
for i in f:
ip = i.strip()
os.system("ping " + ip + " -n 500")
f.close()
test.txt:
10.1.1.1
10.1.1.2
10.2.1.1
10.2.1.1
解决方法:
这是一个方便的模块:progress_bar
.
它足够简短.阅读有关实现自己的想法的资源.
我希望这是一段非常简单的代码,可以使事情变得更清楚:
import time, sys
# The print statement effectively treats '\r' as a newline,
# so use sys.stdout.write() and .flush() instead ...
def carriage_return_a():
sys.stdout.write('\r')
sys.stdout.flush()
# ... or send a terminal control code to non-windows systems
# (this is what the `progress_bar` module does)
def carriage_return_b():
if sys.platform.lower().startswith('win'):
print '\r'
else:
print chr(27) + '[A'
bar_len = 10
for i in range(bar_len + 1):
# Generate a fixed-length string of '*' and ' ' characters
bar = ''.join(['*'] * i + [' '] * (bar_len - i))
# Insert the above string and the current value of i into a format
# string and print, suppressing the newline with a comma at the end
print '[{0}] {1}'.format(bar, i),
# Write a carriage return, sending the cursor back to the beginning
# of the line without moving to a new line.
carriage_return_a()
# Sleep
time.sleep(1)
正如其他人所观察到的那样,您仍然需要知道文件中的总行数才能拥有非常有意义的进度条.最简单的方法是读取整个文件以获得行数.但这很浪费.
将其整合到一个简单的类中并不是一件容易的事……现在您可以创建进度条,并在感兴趣的值发生变化时对其进行update().
class SimpleProgressBar(object):
def __init__(self, maximum, state=0):
self.max = maximum
self.state = state
def _carriage_return(self):
sys.stdout.write('\r')
sys.stdout.flush()
def _display(self):
stars = ''.join(['*'] * self.state + [' '] * (self.max - self.state))
print '[{0}] {1}/{2}'.format(stars, self.state, self.max),
self._carriage_return()
def update(self, value=None):
if not value is None:
self.state = value
self._display()
spb = SimpleProgressBar(10)
for i in range(0, 11):
time.sleep(.3)
spb.update(i)