Create broken symlink using Python

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

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

+4
source share
4 answers

Such an error occurs when trying to create a symbolic link in a nonexistent directory. For example, the following code will not work if /tmp/subdir does not exist:

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

But this should work 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) 
+7
source

A file to create a symbolic link is not required. The following example demonstrates creating a symbolic link to a nonexistent file:

First check if there is a file named foobar in /home/wieslander/tmp :

 [ wieslander@rizzo tmp]$ ls -l /home/wieslander/tmp/foobar ls: cannot access /home/wieslander/tmp/foobar: No such file or directory 

Create a symlink named brokensymlink pointing to /home/wieslander/tmp/foobar :

 [ wieslander@rizzo tmp]$ python Python 2.5.2 (r252:60911, Sep 30 2008, 15:42:03) [GCC 4.3.2 20080917 (Red Hat 4.3.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.symlink('/home/wieslander/tmp/foobar', 'brokensymlink') 

Ensure that the symbolic link is created and that the destination still does not exist:

 [ wieslander@rizzo tmp]$ ls -l brokensymlink lrwxrwxrwx 1 wieslander wieslander 27 19 nov 13.13 brokensymlink -> /home/wieslander/tmp/foobar [ wieslander@rizzo tmp]$ ls -l /home/wieslander/tmp/foobar ls: cannot access /home/wieslander/tmp/foobar: No such file or directory 
+3
source

Are you sure you are invoking a symbolic link with the correct parameters?

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

This should create a symlink to / usr / bin / python from python in the current working directory.

0
source

This could be your answer:

 $ python Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.symlink('/this/does/not/exist', 'broken') >>> os.symlink('broken', '/this/does/not/exist') Traceback (most recent call last): File "<stdin>", line 1, in <module> OSError: [Errno 2] No such file or directory 

Have you canceled the arguments? Or are you just trying to create a symbolic link in a directory that does not exist?

0
source

All Articles