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

发布于 2025-01-05 04:22:58 字数 342 浏览 2 评论 0原文

我正在读取文本文件中的行形式,然后每行执行操作。由于文本文件的大小和每个动作的时间 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()

测试.txt:

10.1.1.1
10.1.1.2
10.2.1.1
10.2.1.1

I'm reading lines form in a text file and then performing actions per line. Due to the size of the text file and the time of each action 500 => seconds. I would like to be able to view the progress but not sure where to start.

Here is an example script I'm using, how would write that for this?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不交电费瞎发啥光 2025-01-12 04:22:58

这是一个方便的模块: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)

正如其他人所观察到的,您仍然需要知道文件中的总行数才能获得非常有意义的进度条。最直接的方法是读取整个文件以获取行数;但这相当浪费。

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

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)

Here's a handy module: progress_bar.

It's short and simple enough; read the source for ideas on implementing your own.

Here's a very simple piece of code that, I hope, makes things clearer:

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)

As others have observed, you still need to know the total number of lines in the file in order to have a very meaningful progress bar. The most straightforward way to do that is to read the whole file to get a line count; but that's rather wasteful.

Incorporating this into a simple class isn't too hard... now you can create the progress bar and update() it whenever the value of interest changes.

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)
若无相欠,怎会相见 2025-01-12 04:22:58

另一个起点可能是 progressbar 模块。

您还可以[此处]下载源代码,tar.gz 内有一个example.py 文件包含一些很好的示例。

Another starting point could be the progressbar module.

You can also download the source code [here], inside the tar.gz there's an example.py file with some good examples.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文