Python 用于读取文本文件中的行的进度条

Python 用于读取文本文件中的行的进度条,python,progress-bar,progress,text-files,Python,Progress Bar,Progress,Text Files,我读取文本文件中的行表单,然后每行执行操作。由于文本文件的大小和每个操作的时间,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

我读取文本文件中的行表单,然后每行执行操作。由于文本文件的大小和每个操作的时间,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
这里有一个方便的模块:

它很短很简单;阅读源代码,了解如何实现自己的想法

下面是一段非常简单的代码,我希望它能让事情变得更清楚:

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)
正如其他人所观察到的,为了获得一个非常有意义的进度条,您仍然需要知道文件中的行总数。最简单的方法是读取整个文件以获得行计数;但那是相当浪费的

将其合并到一个简单的类中并不难。。。现在,您可以创建进度条,并在感兴趣的值发生变化时更新它

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)

另一个起点可能是模块


您也可以下载源代码,在tar.gz中有一个
example.py
文件,其中包含一些好的示例。

@nightcracker抱歉,我迷路了。500=表示ping-n选项中的数据包计数。导入时间会有什么帮助?问题是,要测量进度(以处理的行为单位),您需要找到文件中的总行数。或者,您可以获取文件的大小,并使用该大小生成统计信息。无论哪种方式,您都需要找到要完成的处理的“总量”,然后在循环中的每次迭代中,您都知道自己是完成方式的
100*当前迭代/total\u迭代
%。谢谢,问题是我太迷茫了,需要把它解释清楚。。我一直在试图解决如何实现它或创建一个,但我一直在思考它,开始感到困惑..感谢它有点道理,正如其他人所观察到的,你仍然需要知道文件中的总行数,以便有一个非常有意义的进度条,我发现了这一部分。。。它只是把它啮合在一起。。没有什么比现在的尝试和错误更重要的了。。