Skip to content

Instantly share code, notes, and snippets.

@ymmt2005 ymmt2005/atomic_rename.py
Last active Jul 4, 2016

Embed
What would you like to do?
atomic_rename.py
#!/usr/bin/python3
from argparse import ArgumentParser
import os
from os.path import dirname, realpath
from tempfile import NamedTemporaryFile
def syncdir(d: str):
fd = os.open(d, os.O_RDONLY|os.O_DIRECTORY)
os.fsync(fd)
os.close(fd)
def atomic_rename(f: str):
d = dirname(realpath(f))
with NamedTemporaryFile(dir=d, delete=False) as t:
t.write(b'abc\n')
t.flush()
os.fsync(t.fileno())
os.rename(t.name, f)
print('rewrote', f)
syncdir(d)
def main():
p = ArgumentParser()
p.add_argument('file', metavar='FILE')
ns = p.parse_args()
atomic_rename(ns.file)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.