I want create a symlink, overwriting an existing file or symlink if needed.
I've discovered that os.path.exists
only returns True
for non-broken symlinks, so I'm guessing that any test must also include os.path.lexists
.
What is the most atomic way to implement ln -sf
in python? (Ie, preventing a file being created by another process between deletion and symlink creation)
Differentiation: This question doesn't specify the atomic requirement
This code tries to minimise the possibilities for race conditions:
Note:
If the function is interrupted (e.g. computer crashes), an additional random link to the target might exist.
An unlikely race condition still remains: the symlink created at the randomly-named
temp_link_name
could be modified by another process before replacinglink_name
.I raised a python issue to highlight the issues of
os.symlink()
requiring the target not exist.Credit to Robert Seimer's input.