Last active
July 4, 2016 09:00
-
-
Save ymmt2005/97c732fa2551650c16703cba8705c124 to your computer and use it in GitHub Desktop.
atomic_rename.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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