从python2.7.6中的stdin读取。系统stdout.flush()而python u没有

2024-05-16 23:48:59 发布

您现在位置:Python中文网/ 问答频道 /正文

似乎很多人都在为获得缓冲区、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,都会发生这种情况。在

谢谢你给我的任何指导。在


Tags: inreforifmatchstdinsysline
3条回答

sys.stdin只是一个file对象,因此如果使用readlines()则读取将继续,直到所有行都被读取。只有在按下Ctrl+D(在Linux中)时才会发生这种情况。试着一行一行地读,像这样:

#!/usr/bin/env python
import sys,re


while True:

     line = sys.stdin.readline()
     m = re.search("end", line)
     if m:  
        break
     else:
        print "I read:" + line

解决方法很简单:

for line in sys.stdin:
     # process line

由于sys.stdin是一个类似于文件的对象,因此迭代它一次生成一行。在

下面是一些例子系统标准一次一行。它们不需要使用python-u选项。在

#! /usr/bin/env python

import sys

def main():
    count = 1
    while True:
        line = sys.stdin.readline()
        if line == '':
            break   #EOF encountered

        print "%3d: [%s]" % (count, line[:-1])
        count += 1


if __name__ == '__main__':
    main()

如果您使用的是Linux/Unix,这个版本更好,因为它提供了行编辑功能。在

^{pr2}$

相关问题 更多 >