Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create broken symlink with Python

Tags:

python

symlink

ln

Using Python I want to create a symbolic link pointing to a path that does not exist. However os.symlink just complains about "OSError: [Errno 2] No such file or directory:".. This can easily be done with the ln program, but how to do it in Python without calling the ln program from Python?

Edit: somehow I really messed this up :/ ... both answers below is correct

like image 497
Mathias Avatar asked Dec 18 '22 04:12

Mathias


1 Answers

Such error is raised when you try to create a symlink in non-existent directory. For example, the following code will fail if /tmp/subdir doesn't exist:

os.symlink('/usr/bin/python', '/tmp/subdir/python')

But this should run successfully:

src = '/usr/bin/python'
dst = '/tmp/subdir/python'

if not os.path.isdir(os.path.dirname(dst)):
    os.makedirs(os.path.dirname(dst))
os.symlink(src, dst)
like image 166
Denis Otkidach Avatar answered Jan 04 '23 05:01

Denis Otkidach