gpt4 book ai didi

python - 从 Python 2.7.6 中的 stdin 读取。 Sys.stdout.flush() 和 python -u 不起作用

转载 作者:行者123 更新时间:2023-12-01 04:59:52 25 4
gpt4 key购买 nike

似乎很多人一直在努力让缓冲区、标准输入和粗壮的数据在多种 Python 风格中工作。我正在用 Python 2.7.6 编写一个脚本来从 stdin 读取、执行正则表达式匹配并打印匹配字符串的列表。

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 block 来打印任何内容,而且我似乎找不到任何有关如何在从 stdin 读取时运行/打印进程的文档。

需要明确的是,无论我是否使用 -u 标志调用 Python,都会发生这种情况。

感谢您给我的任何指导。

最佳答案

下面是一些一次读取一行 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,这个版本更好,因为它为您提供行编辑。

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

关于python - 从 Python 2.7.6 中的 stdin 读取。 Sys.stdout.flush() 和 python -u 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com