Python 3.x 读取文件时删除子进程缓冲区

Python 3.x 读取文件时删除子进程缓冲区,python-3.x,linux,Python 3.x,Linux,我需要实时监控一个文件,并提取某些信息来通知用户进度。基本上类似于“tail-f”,它立即输出添加到文件中的行。问题是,我似乎有一个缓冲问题,延迟获得最新的线路 这是我的密码: f = subprocess.Popen(['tail','-F','/myfile'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,bufsize=1, universal_newlines=True) while True: line = f.stdout.re

我需要实时监控一个文件,并提取某些信息来通知用户进度。基本上类似于“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.configure(line\u buffering=True)
。将
Popen
对象内的流设置为自动使用
flush

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

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

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

使用
f.stdout.configure(line\u buffering=True)
。将
Popen
对象内的流设置为自动使用
flush

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

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

Try buffsize parameter=0一个更好的方法(而不是tail)可以改为选择库:很遗憾,缓冲区仍然处于活动状态。@JBernardo您可以显示一些代码吗?Try buffsize parameter=0一个更好的方法(而不是tail)可以改为选择库:很遗憾,缓冲区仍处于活动状态。@JBernardo请显示一些代码好吗?