似乎很多人都在为获得缓冲区、stdin和stout跨多种Python风格而努力。我正在用python2.7.6编写一个脚本,从stdin读取,进行regex匹配,并打印匹配字符串的列表。在
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,都会发生这种情况。在
谢谢你给我的任何指导。在
sys.stdin
只是一个file
对象,因此如果使用readlines()
则读取将继续,直到所有行都被读取。只有在按下Ctrl+D(在Linux中)时才会发生这种情况。试着一行一行地读,像这样:解决方法很简单:
由于
sys.stdin
是一个类似于文件的对象,因此迭代它一次生成一行。在下面是一些例子系统标准一次一行。它们不需要使用python
-u
选项。在如果您使用的是Linux/Unix,这个版本更好,因为它提供了行编辑功能。在
^{pr2}$相关问题 更多 >
编程相关推荐