如果我在执行文件I / O操作时突然关闭脚本,会发生什么情况? [英] What would happen if I abruptly close my script while it's still doing file I/O operations?

查看:123
本文介绍了如果我在执行文件I / O操作时突然关闭脚本,会发生什么情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我的问题:我正在编写一个脚本来检查我的网站是否正常运行,基本思路是每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中得到什么?我得到这个我(一个不完整的行),或者完整的行或行甚至没有添加?

希望有人知道答案。

解决方案

根据 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆