【问题标题】:Create broken symlink with Python使用 Python 创建损坏的符号链接
【发布时间】:2009-11-19 12:03:53
【问题描述】:

使用 Python 我想创建一个指向不存在路径的符号链接。然而 os.symlink 只是抱怨“OSError: [Errno 2] No such file or directory:”.. 这可以通过 ln 程序轻松完成,但如何在 Python 中不调用ln 来自 Python 的程序?

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

【问题讨论】:

  • 你用的是什么版本的python?
  • 您使用的是什么操作系统,您确定符号链接的目标目录存在吗?
  • 您能在此处添加交互式会话的输出吗?我尝试了 Pär Wieslander 的答案,它在我的 Solaris 盒子和 Windows(在 cygwin 中)上运行良好。但是,如果你颠倒参数,我会得到和你一样的错误。

标签: python symlink ln


【解决方案1】:

当您尝试在不存在的目录中创建符号链接时会引发此类错误。例如,如果/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)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      这应该在当前工作目录中从 python 创建一个指向 /usr/bin/python 的符号链接。

      【讨论】:

      • 糟糕,我应该更仔细地阅读这个问题。对于那个很抱歉。看来您需要有文件才能链接到它。
      【解决方案4】:

      这可能是你的答案:

      $ 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
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-21
        • 2017-12-14
        • 2016-04-19
        • 1970-01-01
        • 2018-09-05
        相关资源
        最近更新 更多