文本文件读取行的进度条

3 投票
2 回答
4324 浏览
提问于 2025-04-17 12:58

我正在从一个文本文件中读取每一行,然后对每一行执行一些操作。因为这个文本文件很大,每次操作需要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

2 个回答

1

另一个可以开始的地方是 progressbar 模块。

你也可以在 这里 下载源代码,压缩包里面有一个 example.py 文件,里面有一些不错的示例。

3

这里有一个很实用的模块: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)

撰写回答