【发布时间】:2014-10-22 03:25:42
【问题描述】:
似乎很多人一直在努力让缓冲区和标准输入以及 stout 在多种 Python 风格中工作。我正在 Python 2.7.6 中编写一个脚本来读取标准输入,进行正则表达式匹配,并打印匹配字符串的列表。
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 读取 EOF 块以打印任何内容,我似乎找不到任何关于如何让进程在从 stdin 读取时运行/打印的文档。
需要明确的是,无论我是否使用 -u 标志调用 Python,都会发生这种情况。
感谢您能给我的任何指导。
【问题讨论】:
-
.readlines()将一次性读取整个文件(或标准输入)...您需要使用.read()并自己查找换行符。 -
原谅我,但我已经阅读了文件对象的文档,我不清楚如何使用换行符来遍历 sys.stdin.read() 将返回的字符串。我是否应该尝试使用设定的字节数从标准输入读取,然后将字符串解析为一个列表,然后遍历每个列表,直到我读完整个文件?
-
@DanBurkhardt:你试过简单的
for line in sys.stdin:吗? -
@JohnZwinck 我没有,但这确实有效。谢谢!我想我对 sys.stdin 是一个文件对象感到困惑,所以我没有一直在寻找文件对象的方法。
-
@DanBurkhardt:不客气。我将其添加为答案,因为它似乎对您有用。
标签: python python-2.7 stdout stdin eof