Reading from stdin in Python 2.7.6. Sys.stdout.flush() and python -u doesn't work
Question: It seems like many people have been struggling with getting buffers and stdin
and stout working across many flavors of Python. I'm writing a script in
Python 2.7.6 to read from stdin, do a regex match, and print a list of
matching strings.

    
    
    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
    

Like many before me have found, this waits until it reads an EOF block from
stdin to print anything and I can't seem to find any documentation on how to
have the process run/print as it reads from stdin.

To be clear, this happens regardless of whether or not I call Python with the
-u flag.

Thank you for any guidance you can give me.


Answer: Here are some examples that read sys.stdin a line at a time. They do _not_
require the use of the python `-u` option.

    
    
    #! /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()
    

If you are using Linux / Unix, this version is better because it gives you
line editing.

    
    
    #! /usr/bin/env python
    
    import sys
    import readline
    
    def main():
        count = 1
        while True:
            try:
                line = raw_input()
                print "%3d: [%s]" % (count, line)
                count += 1
            except EOFError:
                break
    
    
    if __name__ == '__main__':
        main()
    

