~smoser/cloud-init/azure_dhcp

1261 by Scott Moser
re-add atomic_helper
1
#!/usr/bin/python
2
# vi: ts=4 expandtab
3
4
import json
5
import os
6
import tempfile
7
8
9
def atomic_write_file(path, content, mode='w'):
10
    tf = None
11
    try:
12
        tf = tempfile.NamedTemporaryFile(dir=os.path.dirname(path),
13
                                         delete=False, mode=mode)
14
        tf.write(content)
15
        tf.close()
16
        os.rename(tf.name, path)
17
    except Exception as e:
18
        if tf is not None:
19
            os.unlink(tf.name)
20
        raise e
21
22
23
def atomic_write_json(path, data):
24
    return atomic_write_file(path, json.dumps(data, indent=1,
25
                                              sort_keys=True) + "\n")