Skip to content

Instantly share code, notes, and snippets.

@ymmt2005
Last active July 4, 2016 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ymmt2005/97c732fa2551650c16703cba8705c124 to your computer and use it in GitHub Desktop.
Save ymmt2005/97c732fa2551650c16703cba8705c124 to your computer and use it in GitHub Desktop.
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