How to streamingly read text file and display whenever updated text

galeomaga at gmail.com galeomaga at gmail.com
Sat Oct 5 23:17:32 EDT 2013


Joost Molenaar於 2013年10月5日星期六UTC+8下午7時02分05秒寫道:
> A bit of googling found me this:
> 
> http://www.linux-support.com/cms/implementation-of-tail-in-python/
> 
> 
> 
> import time
> 
> import sys
> 
> 
> 
> def tail_f(file):
> 
>   interval = 1.0
> 
>   while True:
> 
>     where = file.tell()
> 
>     line = file.readline()
> 
>     if not line:
> 
>       time.sleep(interval)
> 
>       file.seek(where)
> 
>     else:
> 
>       yield line

After tried many times, updated text file is not shown, it only print text at the first time. 

#!/usr/bin/python
import time 
import sys 
import thread

def tail_f(filehandler): 
  interval = 1.0 
  while True: 
	try:
		line = filehandler.readline()	
		where = filehandler.tell()
		if not line: 
			time.sleep(interval) 
			filehandler.seek(where) 
		else: 
			yield line 
	except:
		print "tail_f error"
	

def readfile(systemname):
	try:
		filehandler = open("/home/martin/Downloads/a.txt","r");
		while 1:
			#for line in tail_f(filehandler):
			#	print line 
			try:				
				interval = 1.0 
				line = filehandler.readline()	
				where = filehandler.tell()
				if not line: 
					time.sleep(interval) 
					filehandler.seek(where) 
					print where
				else: 
					print line 
			except:
				print "tail_f error"
	except:
		print "Error: readfile"

if __name__ == '__main__':
	try:
		thread.start_new_thread( readfile, ("Thread-1", ) )
	except:
   		print "Error: unable to start thread"

	while 1:
   		pass



More information about the Python-list mailing list