首页 > 解决方案 > 是什么导致 http 请求覆盖由 file.write() 创建的内部缓冲区?

问题描述

我试图在datetime.datetime.now()for 循环的每次迭代之后写入一个文本文件,这样我就可以计算每秒对我们的 API 进行的调用次数。这是我的工作代码

import requests
import datetime
import config

# create a file with a timestamp starting at runtime.
with open('timelog-' + str(datetime.datetime.now().strftime("%y-%m-%d--%H-%S")) + '.txt', 'a') as log_time:
    for x in range(10):
        req = requests.post('https://' + config.env.lower() + '.website.com/args'
                                            + config.cli + '/args/'
                                            + config.con + '/args/?args='
                                            + config.cel + '&date='
                                            + config.req + '&args', headers=config.head)
        log_time.write(str(datetime.datetime.now().replace(microsecond=0)) + "\n")
        log_time.flush()

现在,让我感到困惑的是,如果我要注释掉req,我就不需要包含log_time.flush(). 同样,如果我要删除log_time.flush(),log_time.write()将无法正常运行,而是以空白文件结束。

这种行为有什么特别的原因吗?

标签: pythonpython-3.xpython-requests

解决方案


简短的回答:什么都没有- 见下文无法重现


文件对象缓冲区在内部写入,flush表明现在是向您的操作系统提供累积数据的好时机。您的操作系统决定他们是否以及何时将数据提供给磁盘控制器,磁盘控制器也有缓冲区并在他们认为合适的时候执行物理写入。

您不能保证仅通过调用来创建文件flush- 它只是一个“建议”,您无法控制链中的其他“决策者”。

您的操作系统/光盘控制器应该“透明地”处理文件——如果它没有写入它们并且您请求它,它应该提供它已经缓冲的内容(如果尚未物理写入)。

请参阅 fe文件系统写入缓冲区通常在多少秒后被刷新? 或者 python 多久刷新一次文件?


除此之外 -无法重现

import requests
import datetime 

# create a file with a timestamp starting at runtime.
name = 'timelog-' + str(datetime.datetime.now().strftime("%y-%m-%d--%H-%S")) + '.txt'
with open(name, 'a') as log_time:
    for x in range(10):
        req = requests.post('https://www.google.de/search?q=google')
        log_time.write(str(datetime.datetime.now()) + "\n")

with open(name) as f:
    print(f.read())

输出:

2018-11-03 10:46:31.220314
2018-11-03 10:46:31.258467
2018-11-03 10:46:31.296618
2018-11-03 10:46:31.333934
2018-11-03 10:46:31.372513
2018-11-03 10:46:31.409757
2018-11-03 10:46:31.447643
2018-11-03 10:46:31.485454
2018-11-03 10:46:31.523937
2018-11-03 10:46:31.562102

推荐阅读