用Python创建损坏的符号链接

7 投票
4 回答
13014 浏览
提问于 2025-04-15 16:10

我想用Python创建一个指向不存在路径的符号链接。但是使用os.symlink时,它总是报错:“OSError: [Errno 2] 没有这样的文件或目录”。这个操作在ln程序中很简单,但我想知道怎么在Python中做到这一点,而不调用ln程序。

编辑:我真的搞砸了 :/ ... 下面的两个答案都是正确的

4 个回答

0

你确定你在用正确的参数调用symlink吗?

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

这段代码应该是在当前工作目录下,从python创建一个指向/usr/bin/python的符号链接。

3

创建符号链接(symlink)时,目标文件并不需要真的存在。下面的例子就展示了如何为一个不存在的文件创建符号链接:

首先,检查一下在 /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

然后,创建一个名为 brokensymlink 的符号链接,指向 /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')

最后,检查一下这个符号链接是否创建成功,并确认目标文件仍然不存在:

[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
11

当你尝试在一个不存在的文件夹里创建一个符号链接时,就会出现这样的错误。比如,如果 /tmp/subdir 这个文件夹不存在,下面的代码就会失败:

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

但是,如果文件夹存在,这段代码就能顺利运行:

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)

撰写回答