많은 사람들이 버퍼와 stdin을 얻는 데 어려움을 겪고 있으며 많은 Python을 사용하고 있습니다. Python 2.7.6에서 stdin을 읽고, 정규식 매치를 수행하고, 일치하는 문자열 목록을 출력하는 스크립트를 작성하고 있습니다. 저를 발견하기 전에 아무것도 인쇄하여 stdin에서 EOF 블록을 읽고 난 그게에서 읽는 프로세스 실행/인쇄를하는 방법에 대한 문서를 찾을 수없는 것까지 많은처럼 Python 2.7.6에서 stdin에서 읽기. Sys.stdout.flush()와 python -u가 작동하지 않습니다.
import re, sys
barcodes=["The barcodes are:"]
curr=barcodes[0]
#iterate through stdin
for line in sys.stdin.readlines():
#do regex match in line
match = re.search('(?<=\:)[GATC]{6}', line.rstrip()).group(0)
matched = 0
#see if match has been seen before
if (match == curr):
matched = 1
print "matched curr"
else:
for a , val in enumerate(barcodes):
if (match == val):
print str(a) + " : " + val + " barcodes[a] " + str(barcodes[a])
curr = barcodes[a]
print curr
matched = 1
print "matched iteration"
#if match hasn't been seen before
if (matched == 0):
sys.stdout.write("NEW match")
sys.stdout.flush()
barcodes.append(match)
#print report of barcodes
for i in barcodes:
print i
이 기다립니다 stdin.
파이썬을 -u 플래그로 호출하는지 여부에 관계없이이 문제는 발생합니다.
안내해 주셔서 감사합니다.
'.readlines()'는 전체 파일 (또는 stdin)을 한 번에 읽습니다.'.read()'를 사용하고 직접 개행을 찾아야합니다. – thebjorn
용서해주세요. 그러나 파일 객체에 대한 문서를 읽었으며, 줄 바꿈을 사용하여 sys.stdin.read()가 반환 할 문자열을 반복하는 방법이 나에게 불분명합니다. 설정된 바이트 수를 사용하여 stdin에서 읽으려고하면 문자열을 목록으로 구문 분석 한 다음 전체 파일을 읽을 때까지 각 목록을 반복합니다. –
@ DanBurkhardt : 간단히'for line in sys.stdin :'시도해 보셨습니까? –