python - 是什么导致 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()
将无法正常运行,而是以空白文件结束。
这种行为有什么特别的原因吗?
解决方案
简短的回答:什么都没有- 见下文无法重现。
文件对象缓冲区在内部写入,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
推荐阅读
- c# - LastIndexOf 错误?
- gitlab - 无法从 Gitlab 内的 Swagger UI 调用外部 API。内容安全策略错误
- elasticsearch - ElasticSearch - 结合过滤器和复合查询以获得独特的字段组合
- logging - Serilog 没有方法“.ForContext()”
- ssl - 如何在我的 kubernetes 服务中使用证书管理器letsencrypt-prod?
- image-upload - 如何在富文本编辑器中更改图像上传路径?
- python - 使用python将文件下载到虚拟服务器
- model - Epsilon eol 无法识别元模型实体
- ruby-on-rails - Google App Engine 部署耗时超过 20 分钟
- python - 对于大型 DataFrame,在 pandas 中回测交易机器人的最佳方法,无需逐行测试策略?