5

使用 Python 我想创建一个指向不存在路径的符号链接。然而 os.symlink 只是抱怨“OSError: [Errno 2] No such file or directory:”.. 这可以很容易地用ln程序完成,但是如何在 Python 中做到这一点而不从 Python 调用ln程序呢?

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

4

4 回答 4

9

当您尝试在不存在的目录中创建符号链接时会引发此类错误。例如,如果/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)
于 2009-11-19T12:24:41.453 回答
3

该文件不需要存在即可创建符号链接。以下示例演示如何创建指向不存在文件的符号链接:

首先,检查是否没有名为foobarin的文件/home/wieslander/tmp

[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
于 2009-11-19T12:19:25.473 回答
0

你确定你用正确的参数调用符号链接吗?

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

这应该从当前工作目录中的 python 创建到 /usr/bin/python 的符号链接。

于 2009-11-19T12:08:17.757 回答
0

这可能是你的答案:

$ 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

你是否颠倒了论点?或者您只是想在一个不存在的目录中创建符号链接?

于 2009-11-19T12:29:04.247 回答