2017-04-07 1 views
0

stdin (감속기에서 스트리밍 하프 아웃)을 통해 입력을 읽고 있습니다.파이썬에서 표준 입력 (stdin)의 마지막 레코드를 감지하십시오.

마지막 레코드가 들어올 때를 감지해야합니다. stdin 데이터에서 루프를 실행하고 있습니다. 내가 total_cnt 다음 레코드가 스트림에서 나가서 나중에 계산 stdin 에서 레코드를 읽을 때

나는 즉시 stdin 전체 기록을 계산하는 첫번째 후 다시 업무 처리를 진행 읽을 수는 있지만를 읽으려고 처리를 위해 stdin을 읽으려고하면 stdin에 레코드가 없습니다.

total_cnt = 0 

for line in stdin: 
    total cnt += 1 

for line in stdin: 
    ##Some Processing## 

내가 두 번 해당 위치에서 데이터를 어딘가에 stdin를 저장하고 읽을 수 없다 (1. 총 레코드 수 및 2. 데이터 처리).

마지막 레코드가 stdin에서 왔을 때 감지 할 수있는 방법이 있습니까?

저는 python 버전 2.7.11을 사용하고 있으며 이것을 Hadoop 감속기의 접근 방식으로 구현해야합니다.

+0

이 http://stackoverflow.com/a/24199042/5987 –

답변

1

새 줄을 가져올 때마다 이전 줄을 처리하십시오. 루프가 종료되면 line에 마지막으로 처리되지 않은 행이 표시됩니다.

예 :

old_line = None 
for line in range(10): 
    if old_line is None: 
     old_line = line 
     continue # skip processing on the first loop: we'll make it up after 
    print "Do stuff with: %i" % old_line 
    old_line = line 
print "Double last line: %i" % (line*2) 

제공 :

Do stuff with: 0 
Do stuff with: 1 
Do stuff with: 2 
Do stuff with: 3 
Do stuff with: 4 
Do stuff with: 5 
Do stuff with: 6 
Do stuff with: 7 
Do stuff with: 8 
Double last line: 18 
+0

완벽한하세요! 잘 작동합니다. – XEngineer

관련 문제