读取文件时删除子进程缓冲区



我需要实时监控文件并提取某些信息以通知用户进度。基本上类似于"tail -f"的东西,它立即输出添加到文件中的行。问题是我似乎有一个缓冲问题,延迟获取最新线路。

这是我的代码:

f = subprocess.Popen(['tail','-F','/myfile'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,bufsize=1, universal_newlines=True)
while True:
line = f.stdout.readline()
print (line)
我也尝试过"sys.stdout.write">

和"sys.stdout.flush",但这没有区别。我尝试使用"-u"执行 Python 脚本,但它没有任何改变。

你能帮忙吗?

你走对了路,但使用了错误的流。打电话给flush是正确的想法。但sys.std*是脚本的流,而不是Popen对象中的流。

使用f.stdout.reconfigure(line_buffering=True).这会将Popen对象内的流设置为自动使用flush

除了使用tail,您还可以从文件中读取:

with open('/myfile', buffering=1) as f:
for line in f:  # reads the file line-by line
print(line)

最新更新