我想在Python中输出tail -F或类似的东西,而不会阻塞或锁定。我发现了一些非常古老的代码来做here,但我认为现在必须有更好的方法或库来做同样的事情。谁知道一个?
理想情况下,我有一些类似tail.getNewData()
的东西,每当我想要更多数据时我都可以调用它。
如果你在linux上(因为windows不支持调用select on files),你可以使用subprocess模块和select模块。
import time
import subprocess
import select
f = subprocess.Popen(['tail','-F',filename],\
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
p = select.poll()
p.register(f.stdout)
while True:
if p.poll(1):
print f.stdout.readline()
time.sleep(1)
这将轮询输出管道以获取新数据,并在可用时将其打印出来。通常,time.sleep(1)
和print f.stdout.readline()
将被有用的代码替换。
您可以使用子进程模块而无需额外的选择模块调用。
import subprocess
f = subprocess.Popen(['tail','-F',filename],\
stdout=subprocess.PIPE,stderr=subprocess.PIPE)
while True:
line = f.stdout.readline()
print line
这也将在添加时打印新行,但它会阻塞,直到尾程序关闭,可能使用f.kill()
。
您也可以使用'AWK'命令。 查看更多:http://www.unix.com/shell-programming-scripting/41734-how-print-specific-lines-awk.html awk可用于尾部最后一行,最后几行或文件中的任何行。 这可以从python调用。
如果您使用的是Linux,则可以通过以下方式在python中实现非阻塞实现。
import subprocess
subprocess.call('xterm -title log -hold -e \"tail -f filename\"&', shell=True, executable='/bin/csh')
print "Done"
Python是“包含电池” - 它有一个很好的解决方案:https://pypi.python.org/pypi/pygtail
读取尚未读取的日志文件行。记得上次完成的地方,并从那里继续。
import sys
from pygtail import Pygtail
for line in Pygtail("some.log"):
sys.stdout.write(line)
使用sh module(pip install sh):
from sh import tail
# runs forever
for line in tail("-f", "/var/log/some_log_file.log", _iter=True):
print(line)
[更新]
由于sh.tail与_iter
= True是一个生成器,你可以:
import sh
tail = sh.tail("-f", "/var/log/some_log_file.log", _iter=True)
然后你可以用“getNewData”:
new_data = tail.next()
请注意,如果尾部缓冲区为空,它将阻塞,直到有更多数据(从您的问题来看,在这种情况下您不清楚您想要做什么)。
[更新]
如果你用-F替换-f,这是有效的,但在Python中它会锁定。如果可能的话,我会更有兴趣拥有一个我可以调用以获取新数据的函数。 - 伊莱
容器生成器将尾调用置于一个True循环内并捕获最终的I / O异常将具有与-F几乎相同的效果。
def tail_F(some_file):
while True:
try:
for line in sh.tail("-f", some_file, _iter=True):
yield line
except sh.ErrorReturnCode_1:
yield None
如果文件变得不可访问,则生成器将返回None。但是,如果文件可访问,它仍会阻塞,直到有新数据。对于我来说,在这种情况下你想做什么仍然不清楚。
Raymond Hettinger的方法似乎很不错:
def tail_F(some_file):
first_call = True
while True:
try:
with open(some_file) as input:
if first_call:
input.seek(0, 2)
first_call = False
latest_data = input.read()
while True:
if '\n' not in latest_data:
latest_data += input.read()
if '\n' not in latest_data:
yield ''
if not os.path.isfile(some_file):
break
continue
latest_lines = latest_data.split('\n')
if latest_data[-1] != '\n':
latest_data = latest_lines[-1]
else:
latest_data = input.read()
for line in latest_lines[:-1]:
yield line + '\n'
except IOError:
yield ''
如果文件无法访问或没有新数据,此生成器将返回''。
[更新]
倒数第二个答案围绕文件的顶部,只要数据耗尽就会出现。 - 伊莱
我认为只要尾部进程结束,第二行就会输出最后十行,只要有I / O错误,就会使用-f
。 tail --follow --retry
的行为与我在类似unix的环境中可以想到的大多数情况相差不远。
也许如果你更新你的问题来解释你的真正目标是什么(你想要模仿尾部的原因),你会得到一个更好的答案。
最后一个答案实际上并没有遵循尾部,只是在运行时读取可用的内容。 - 伊莱
当然,tail会默认显示最后10行...你可以使用file.seek将文件指针放在文件的末尾,我会给读者留下一个适当的练习作为练习。
恕我直言,file.read()方法比基于子进程的解决方案更优雅。
实际上,tail -f
文件的唯一可移植方式似乎是从它读取并重试(在sleep
之后)如果read
返回0.各种平台上的tail
实用程序使用特定于平台的技巧(例如BSD上的kqueue
)有效地永久拖尾文件,而不需要sleep
。
因此,纯粹用Python实现一个好的tail -f
可能不是一个好主意,因为你必须使用最小公分母实现(不依赖于特定于平台的黑客)。使用简单的subprocess
打开tail -f
并在单独的线程中迭代这些行,您可以在Python中轻松实现非阻塞的tail
操作。
示例实现:
import threading, Queue, subprocess
tailq = Queue.Queue(maxsize=10) # buffer at most 100 lines
def tail_forever(fn):
p = subprocess.Popen(["tail", "-f", fn], stdout=subprocess.PIPE)
while 1:
line = p.stdout.readline()
tailq.put(line)
if not line:
break
threading.Thread(target=tail_forever, args=(fn,)).start()
print tailq.get() # blocks
print tailq.get_nowait() # throws Queue.Empty if there are no lines to read
所以,这已经很晚了,但我又遇到了同样的问题,现在有一个更好的解决方案。只需使用pygtail:
Pygtail读取尚未读取的日志文件行。它甚至可以处理已旋转的日志文件。基于logcheck的logtail2(http://logcheck.org)
理想情况下,我有类似tail.getNewData()的东西,每当我想要更多数据时我都可以调用它
We've already got one and itsa very nice.只要你想要更多数据,就可以调用f.read()。它将开始读取上一次读取停止的位置,并将读取数据流的末尾:
f = open('somefile.log')
p = 0
while True:
f.seek(p)
latest_data = f.read()
p = f.tell()
if latest_data:
print latest_data
print str(p).center(10).center(80, '=')
要逐行阅读,请使用f.readline()。有时,正在读取的文件将以部分读取的行结束。处理该情况,使用f.tell()查找当前文件位置并使用f.seek()将文件指针移回不完整行的开头。有关工作代码,请参阅this ActiveState recipe。
你可以使用'tailer'库:https://pypi.python.org/pypi/tailer/
它有一个选项来获取最后几行:
# Get the last 3 lines of the file
tailer.tail(open('test.txt'), 3)
# ['Line 9', 'Line 10', 'Line 11']
它也可以跟随一个文件:
# Follow the file as it grows
for line in tailer.follow(open('test.txt')):
print line
如果一个人想要尾巴般的行为,那个人似乎是一个不错的选择。
所有使用tail -f的答案都不是pythonic。
这是pythonic方式:(不使用外部工具或库)
def follow(thefile):
while True:
line = thefile.readline()
if not line or not line.endswith('\n'):
time.sleep(0.1)
continue
yield line
if __name__ == '__main__':
logfile = open("run/foo/access-log","r")
loglines = follow(logfile)
for line in loglines:
print(line, end='')
使Ijaz Ahmad Khan的answer适应只在它们被完全写入时生成行(行以换行符结束)给出了一个没有外部依赖关系的pythonic解决方案:
def follow(file) -> Iterator[str]:
""" Yield each line from a file as they are written. """
line = ''
while True:
tmp = file.readline()
if tmp is not None:
line += tmp
if line.endswith("\n"):
yield line
line = ''
else:
time.sleep(0.1)
if __name__ == '__main__':
for line in follow(open("test.txt", 'r')):
print(line, end='')
另一个选项是tailhead
库,它提供了tail
和head
实用程序的Python版本以及可以在您自己的模块中使用的API。
最初基于tailer
模块,其主要优点是能够按路径跟踪文件,即它可以处理重新创建文件时的情况。此外,它还针对各种边缘情况进行了一些错误修复。