I make a YAML file as a configuration file and read and write python code through the YAML library.
However, this YAML file is read and written by multiple processes, but sometimes the file is corrupted and an error occurs.
As shown below, one character is added below the existing content.
test1: 6511.75277715
test2: false
test3: false
test4: ''
test5: 13.20523311014153
test6: 0.6054349199466555
test7: 0
test8: -1
test9: 33473012.13609034
test1: 6511.75277715
test2: false
test3: false
test4: ''
test5: 13.20523311014153
test6: 0.6054349199466555
test7: 0
test8: -1
test9: 33473012.13609034
4 <<< added letters
I am using python and I am writing a YAML file in the way below. How can I avoid this?
with open(app_setting_dir, "w") as f:
yaml.dump(data, f)
Could you please take a look at the code with the fasteners applied?? What I want is to prevent any .py files other than 1.py from modifying yaml while the 1.py file is running.
app_setting_dir = "./setting/app_setting.yaml"
def read_settings(dir):
with open(dir) as f:
return yaml.safe_load(f)
def write_setting2(data):
ruamel_yaml = ruamel.yaml.YAML(typ="safe")
rw_lock = fasteners.InterProcessReaderWriterLock(app_setting_dir)
with rw_lock.write_lock():
with open(app_setting_dir, "w") as f:
yaml.dump(data, f)
main():
while True:
APP_SETTING_DICT = read_settings(app_setting_dir)
if APP_SETTING_DICT != None:
break
print("read data : ",APP_SETTING_DICT)
APP_SETTING_DICT["test1"] = result[0]
APP_SETTING_DICT["test2"] = result[1]
write_setting2(APP_SETTING_DICT)