Python 文件读取卡在macOS下
我试图在macOS和Python2下读取一个日志文件(这种组合很重要,Python3工作正常,Linux在两个版本中都没有这个问题) 此文件由另一个程序同时写入 问题:Python无法使用新行(在上次阅读周期后出现)。(但我看到它们带有Python 文件读取卡在macOS下,python,macos,Python,Macos,我试图在macOS和Python2下读取一个日志文件(这种组合很重要,Python3工作正常,Linux在两个版本中都没有这个问题) 此文件由另一个程序同时写入 问题:Python无法使用新行(在上次阅读周期后出现)。(但我看到它们带有tail-f)。要复制,您可以在不同终端的同一目录中运行reader和writer(如果您想检查,可以在第三个终端中运行tail-f out.out): 阅读器: import os import time def str_num(line): n_s
tail-f
)。要复制,您可以在不同终端的同一目录中运行reader和writer(如果您想检查,可以在第三个终端中运行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)
作者:
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()
来“重置”文件访问。有没有更聪明的方法来解决这个问题?我想你可能需要一个+:
with open('out.out', 'a+') as _file:
根据本表:
| r r+ w w+ a a+
------------------|--------------------------
read | + + + +
write | + + + + +
create | + + + +
truncate | + +
position at start | + + + +
position at end | + +
请参见以下问题:我想您可能需要一个+:
with open('out.out', 'a+') as _file:
根据本表:
| r r+ w w+ a a+
------------------|--------------------------
read | + + + +
write | + + + + +
create | + + + +
truncate | + +
position at start | + + + +
position at end | + +
请查看以下问题:如果您看到他们使用
tail-f
,并且您没有任何好的解决方案/解决方法,可以选择使用subprocess
运行tail-f
(或者os.popen
,如果您不太在意)。谢谢,但是我更喜欢用标准的python工具来解决这个问题。如果你在tail-f
中看到它们,而你没有任何好的解决方案/解决方法,那么可以选择使用subprocess
来运行tail-f
(或者os.popen
,如果你不在乎的话)。谢谢,但是我更喜欢用标准的python工具来解决这个问题。你检查过你的答案了吗?这对我不起作用。如果我理解正确的话,你会在最后打开文件(并跳过它的内容),这与我的变体不同。你检查过你的答案吗?这对我不起作用。如果我理解正确的话,你会在最后打开这个文件(并跳过它的内容),这和我的变体不同。