如果我在执行文件I / O操作时突然关闭脚本,会发生什么情况? [英] What would happen if I abruptly close my script while it's still doing file I/O operations?
问题描述
好的,下面是一个例子:
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中得到什么?我得到这个我(一个不完整的行),或者完整的行或行甚至没有添加?
希望有人知道答案。
根据 python io文档,缓冲是根据开放函数的缓冲参数处理的。
在这种情况下,默认行为是如果块大小无法确定,则设备的块大小或io.DEFAULT_BUFFER_SIZE。这大概是4096字节。
总之,这个例子不会写任何东西。如果你写了足够长的时间来写入一次或两次缓冲区,那么你将会写入多个缓冲区大小。你可以用flush()手动刷新缓冲区。
(如果指定缓冲区为0,文件模式为二进制,则会得到This i 。这是唯一的方法,但)
正如@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.
In short, that example will write nothing. If you were writing something long enough that the buffer was written once or twice, you'd have multiples of the buffer size written. And you can always manually flush the buffer with flush().
(If you specify buffering as 0 and the file mode as binary, you'd get "This i". That's the only way, though)
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操作时突然关闭脚本,会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!