2012-02-13 2 views
3

텍스트 파일에서 줄 형식을 읽은 다음 줄당 작업을 수행하고 있습니다. 텍스트 파일의 크기와 각 작업의 시간으로 인해 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 
+0

@nightcracker 미안하지만 길을 잃었습니다. 500 = ping -n 옵션의 패킷 수. 수입 시간은 어떻게 도움이됩니까? – onxx

+1

문제는 진행률을 측정하기 위해 (처리 된 행의 관점에서) 파일의 총 줄 수를 찾아야한다는 것입니다. 또는 파일의 크기를 가져 와서 통계를 생성 할 수 있습니다. 어느 쪽이든, 처리 할 총량을 알아야하고 루프를 통해 반복 할 때마다 수행되는 방식의 '100 * current_iteration/total_iterations' %라는 것을 알고 있어야합니다. – prelic

답변

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) 
+0

고마워, 문제는 내가 꽤 길을 잃었고 다소 철자가 필요하다는 것이다. 나는 그것을 구현하거나 하나를 만드는 방법을 찾으려 노력했지만 계속 생각하고 혼란스러워하기 시작했다. – onxx

+0

고마워. 다소 의미가 있습니다. _ 다른 사람들이 보았 듯이, 파일의 줄 수를 알아야 매우 의미있는 진행률을 얻을 수 있습니다. 나는 그 부분을 알아 냈습니다 ... 그저 함께 결합했습니다. 시행 착오 .. – onxx

1

또 다른 출발점은 progressbar 모듈 일 수 있습니다.

소스 코드 [here]을 다운로드 할 수도 있습니다. tar.gz에는 좋은 예제가 들어있는 example.py 파일이 있습니다.