在每次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()
将无法正常运行,相反,我将以空白文件结尾。
此行为是否有任何特殊原因?
答案 0 :(得分:0)
简短答案:没有-参见以下无法复制。
fileobject缓冲区在内部进行写操作,flush
建议将是将累积的数据提供给OS的好时机。您的操作系统将决定是否以及何时向磁盘控制器提供数据,磁盘控制器也具有缓冲区并在认为合适时执行物理写入。
不能保证仅通过调用flush
来创建文件-它只是一个“建议”,您无法控制链中的其他“决定者”。
您的OS /光盘控制器应该“透明地”处理文件-如果尚未写入文件并且您请求它,则它应该提供缓冲的内容(如果尚未实际写入)。
请参见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