繁体   English   中英

使用Python创建损坏的符号链接

[英]Create broken symlink with Python

使用Python我想创建一个指向不存在的路径的符号链接。 然而os.symlink只是抱怨“OSError:[Errno 2]没有这样的文件或目录:”..这可以很容易地用ln程序完成,但是如何在不调用Python的ln程序的情况下在Python中完成它?

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

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

为了创建符号链接,不需要存在该文件。 以下示例演示如何为不存在的文件创建符号链接:

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

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

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

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

这可能是你的答案:

$ 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

你反驳了这些论点吗? 或者您只是尝试在不存在的目录中创建符号链接?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM