我知道这是流处理中的一个典型问题,但我不知道如何在Python中处理它。我有一个由活动进程写入的文件句柄。我想逐行使用该文件句柄中的内容,但我不希望等待读取时陷入死锁。我将继续阅读,直到EOF或60秒的循环阅读,两者以第一位为准。如能就如何做到这一点提出建议,将不胜感激。下面是我对这个问题的伪代码描述。
proc = genprocess("command")
found_a = False
found_b = False
start = time.time()
while True:
line = proc.readline()
while line:
if not found_a and grep(pattern_a, line):
found_a = True
print "Found A, now looking for B"
elif not found_b and grep(pattern_b, line):
found_b = True
print "Found B, all done"
break
if time.time() - start > 60:
break
else:
time.sleep(5)
proc.kill()问题是,这只会在每个间隔上读取一行。相反,我希望循环的内部尽可能多地迭代,但不要阻止等待新内容被写入文件。一旦它阅读了尽可能多的内容,它应该睡上5秒,以允许更多的内容积累。
发布于 2011-03-30 12:41:45
链接到上面的fcntl示例是OK的(除了它将进程置于一个繁忙的循环轮询中),但是我最终使用了"select“来实现所需的或多或少的功能。
started = False
while True:
if (time.time() - start > wait_for) or started:
break
(rlist, wlist, xlist) = select([proc.stdout], [], [], wait_interval)
if len(rlist) > 0:
line = rlist[0].readline() # read one line (this blocks until '\n' is read)
else: # nothing available to read from proc.stdout
print ".",
sys.stdout.flush()
time.sleep(1)
continue
if re.search("daemon started", line):
started = True
if not started:
proc.kill() # don't leave the process running if it didn't start properly如果这是用户可能会使用的CTRL,那么将整个事件放到一个try/ KeyboardInterrupt块中,然后查找proc.kill()就可以调用proc.kill(),而不是让进程在后台运行。
发布于 2011-03-29 02:40:34
如果在Unix环境中运行,可以使用Python的选择模块来等待文件句柄上的数据。此外,您还可以使用Python的fcntl模块将文件句柄更改为非阻塞模式,如这个问题所述。
例如,假设proc变量是支持fileno()的常规文件句柄
file_num = proc.fileno()
old_flags = fcntl.fcntl(file_num, fcntl.F_GETFL)
fcntl.fcntl(file_num, fcntl.F_SETFL, old_flags | os.O_NONBLOCK)https://stackoverflow.com/questions/5467170
复制相似问题