给定以下脚本:
import ConfigParser
from datetime import datetime
import time
def write_stuff():
section = "test"
item = "oh hey there"
conf_filename = "test.conf"
conf = ConfigParser.ConfigParser()
conf.readfp(open(conf_filename, 'r', 0))
timestamp = datetime.now().strftime("%Y-%m-%d_%H%M%S")
conf.set(section, timestamp, item)
with open(conf_filename, "w", 0) as conf_file:
# time.sleep(1)
conf.write(conf_file)
write_stuff()
write_stuff()
write_stuff()
write_stuff()
它只会将一个条目写入文件,如下所示:
$ touch test.conf
$ python tests.py # this is what I've named the above
$ $ cat test.conf
[test]
2012-10-10_231439 = oh hey there
但是,如果您取消注释 time.sleep(1),则会显示所有条目。奇怪的是(对我来说,无论如何),即使你调用了 write_stuff(),并且从 shell 快速连续调用脚本,也会发生这种情况。我认为一旦 Python 退出,任何要写入磁盘的内容都会写入磁盘。这是怎么回事?
环境:Mac OS X 10.8 上的 Python 2.7.3