【问题标题】:What causes a http request to overwrite the internal buffer created by file.write()?是什么导致 http 请求覆盖由 file.write() 创建的内部缓冲区?
【发布时间】:2018-11-03 07:38:13
【问题描述】:

我试图在 for 循环的每次迭代之后将datetime.datetime.now() 写入文本文件,这样我就可以计算每秒对我们的 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() 将无法正常工作,而是以空白文件结束。

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

【问题讨论】:

  • 嗯,离开with 上下文时隐式完成的log_time.close() 包括flush。如果您注释掉 flush,则在 10 个请求中的最后一个请求之后文件是否仍为空白?
  • 是的,老实说,这让我大吃一惊!我让一位同事看了一下,他们说的完全一样,可以理解。

标签: python python-3.x python-requests


【解决方案1】:

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


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

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

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

参见 f.e. After how many seconds are file system write buffers typically flushed?How often does python flush to a file?


除此之外 - 无法复制

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

【讨论】:

  • 感谢您的详尽回答。绝对是一个奇怪的人。我已经重新安装了 PyCharm,代码完全按照预期工作,没有修改,我不确定是什么原因。但是,我将您的答案标记为已接受,因为我在 flush 上学到了一些有价值的信息。再次感谢!
猜你喜欢
  • 2010-10-09
  • 1970-01-01
  • 2011-02-08
  • 2020-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
相关资源
最近更新 更多