我有一个从套接字读取的无限循环。每分钟,我都会将写入位置更改为下一分钟。
问题是我的流中的最后一行在中间被截断并放入下一个文件中。有没有办法告诉它只停在换行符而不是中间?
while ok:
filename1 = datetime.datetime.now().strftime("FILE.0000.%Y.%m.%d.%H.%M.txt")
path="/tmp/" + filename1
file1 = open(path,"a")
ready_to_read, ready_to_write, in_error = select.select(readers, [ ], readers, 300)
for s in ready_to_read:
line = s.recv(1024)
if line:
file1.write(line)
else:
ok = False
file1.flush()
file1.close()
最佳答案
如果只有一个套接字,则不需要select
。使用 makefile
并读取行:
handle = reader.makefile()
for line in handle:
filename = "FILE.0000.{:%Y.%m.%d.%H.%M}.txt".format(datetime.datetime.now())
with open(os.path.join('/tmp', filename), "a") as output:
output.write(line)
关于python - 套接字输出被截断到下一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52104002/