python - 套接字输出被截断到下一个文件

标签 python

我有一个从套接字读取的无限循环。每分钟,我都会将写入位置更改为下一分钟。

问题是我的流中的最后一行在中间被截断并放入下一个文件中。有没有办法告诉它只停在换行符而不是中间?

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/

相关文章:

javascript - 如何从 Javascript/React 发送 AJAX 请求并在 Python REST API 中接收数据

python - 为什么从类 'object' 继承我们创建的任何类是一个好习惯?

python - 在 Tkinter 中接受用户的输入

python - 如何在工作簿中定位图表

python - 根据 Python 中的另一个数据框选择数据框的行

python - 如果值= 1,则pandas数据框打印列

python - 我想更新字典。但它生成,RuntimeError : dictionary changed size during iteration

Python Week Numbers,其中所有周都有 7 天,无论年份是否翻转

python - 如何等待父进程退出子进程?

python - 缺少所需的参数状态Python社交身份验证电子邮件验证