问题描述
这里是我的问题:我正在编写一个脚本来检查我的网站是否正常运行,基本思路是每5分钟获取一次服务器的响应时间和类似的东西,脚本会每次记录信息在检查服务器状态之后。我知道在检查/写入日志的过程中关闭脚本并不好,但是我很好奇,如果有很多服务器需要检查,而且你必须频繁地执行文件I / O,会发生什么如果你突然关闭脚本?好的,下面是一个例子:
True:
DemoFile = open(DemoFile.txt,a)
DemoFile.write(This is an test!)
DemoFile.close()
time .sleep(30)
如果我不小心关闭脚本,而这行 DemoFile .write(This is a test!)
正在运行,我将在DemoFile.txt中得到什么?我得到这个我(一个不完整的行),或者完整的行或行甚至没有添加?
希望有人知道答案。
根据,缓冲是根据开放函数的缓冲参数处理的。
在这种情况下,默认行为是如果块大小无法确定,则设备的块大小或io.DEFAULT_BUFFER_SIZE。这大概是4096字节。
正如@sven指出,python没有做缓冲。当程序终止时,所有打开的文件描述符都将被操作系统关闭并刷新。
here's my question: I'm writing a script to check if my website running all right, the basic idea is to get the server response time and similar stuff every 5 minutes or so, and the script will log the info each time after checking the server status. I know it's no good to close the script while it's in the middle of checking/writing logs, but I'm curious if there are lots of server to check and also you have to do the file I/O pretty frequently, what would happen if you abruptly close the script?
OK, here's an example:
while True:
DemoFile = open("DemoFile.txt", "a")
DemoFile.write("This is a test!")
DemoFile.close()
time.sleep(30)
If I accidentally close the script while this line DemoFile.write("This is a test!")
is running, what would I get in the DemoFile.txt? Do I get "This i"(an incomplete line) or the complete line or the line not even added?
Hopefully somebody knows the answer.
According to the python io documentation, buffering is handled according to the buffering parameter to the open function.
The default behavior in this case would be either the device's block size or io.DEFAULT_BUFFER_SIZE if the block size can't be determined. This is probably something like 4096 bytes.
As @sven pointed out, python isn't doing the buffering. When the program is terminated, all open file descriptors are closed and flushed by the operating system.
这篇关于如果我在执行文件I / O操作时突然关闭脚本,会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!