This code tries to minimise the possibilities for race conditions:
import os
import tempfile
def symlink_force(target, link_name):
'''
Create a symbolic link link_name pointing to target.
Overwrites link_name if it exists.
'''
# os.replace() may fail if files are on different filesystems
link_dir = os.path.dirname(link_name)
while True:
temp_link_name = tempfile.mktemp(dir=link_dir)
try:
os.symlink(target, temp_link_name)
break
except FileExistsError:
pass
try:
os.replace(temp_link_name, link_name)
except OSError: # e.g. permission denied
os.remove(temp_link_name)
raise
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 replacing link_name
.
I raised a python issue to highlight the issues of os.symlink()
requiring the target not exist.
Credit to Robert Seimer's input.
ln -s file tmplink
, thenmv tmplink link
is atomic. – Jointressln -sf
itself is not actually atomic. GNU Coreutils internally implements the solution that @Jointress proposed (and that the currently-accepted answer implements); FreeBSD and Busybox simply delete the destination file before linking. So "par" is actually pretty easy to clear for this. – Aldwin