我想用Python2在macOS下讀取一個日誌文件(這個組合很重要,Python 3工作正常,Linux在這兩個版本中都沒有這個問題)。在macOS下卡住的文件
該文件是由另一個程序同時寫入的。
問題:新行(在上一次讀取循環後出現)不適用於Python。 (但我看到他們與tail -f
)。要重現,你可以(在第三終端和tail -f out.out
如果你想檢查)運行在不同的終端相同的目錄讀寫器:
讀者:
import os
import time
def str_num(line):
n_s = line.find('#')
n_e = line[n_s:].find(' ')
print(line)
return int(line[n_s+1: n_s + n_e])
with open('out.out', 'rt') as _file:
while True:
os.path.getsize('out.out')
lines = _file.readlines(1000)
n1 = n2 = -1
if lines:
n1 = str_num(lines[0])
n2 = str_num(lines[-1])
print("%s (%s - %s)" % (len(lines), n1, n2))
time.sleep(1)
作者:
import time
num = 0
with open('out.out', 'w', buffering=1)as _file:
while True:
_file.write("*** String #%s ***\n" % num)
if not num % 100: print(num)
num += 1
time.sleep(0.01)
我發現的一種解決方法是使用tell()
和seek()
來重置文件訪問權限。有沒有更聰明的方法來解決這個問題?
如果你看到他們與'尾巴-f'你沒有任何好的解決方案/解決方法,一個選項可能是使用'subprocess'來運行'tail -f'(或者如果你真的不在乎的話,可以使用'os.popen')。 – zneak
謝謝,但我更喜歡用標準的Python工具來解決這個問題。 – greyfenrir